Ryan
Ryan

Reputation: 8241

Calling Python constructor with default arguments

Suppose you have a Python class whose constructor looks something like this:

 def __init__(self,fname=None,data=[],imobj=None,height=0,width=0):

and you want to create an instance of it but only provide the fname and imobj inputs. Would the correct way to do this be

thing = Thing(f_name, None, im_obj, None, None)

or is there a preferred way of making this call?

Upvotes: 0

Views: 159

Answers (2)

user2555451
user2555451

Reputation:

You can just do:

thing = Thing(f_name=value1, im_obj=value2)

Note that you do not actually need the f_name= in this case since fname is the first parameter (besides self, which is passed implicitly). You could just do:

thing = Thing(value1, im_obj=value2)

But I personally think that the first solution is more readable. It makes it clear that we are only changing the values of f_name and im_obj while leaving every other parameter to its default value. In addition, it keeps people from wondering what parameter value1 will be assigned to.

Also, you almost never want to have a mutable object such as a list be a default argument. It will be shared across all calls of the function. For more information, see "Least Astonishment" and the Mutable Default Argument

Upvotes: 6

fredtantini
fredtantini

Reputation: 16556

You can instanciate with:

thing = Thing(f_name, imobj=im_obj)

Other named arguments will be set to default.

You can also pass a dict to the constructor:

>>> argDict={"fname": f_name, "imobj": im_obj}
>>> thing = Thing(**argDict)

This will unpack the dict values. See keyword arguments.

Upvotes: 0

Related Questions