0

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?

2
  • Just use named arguments: "Thing(fname=f_name, imobj=im_obj)", everything else defaults. Commented Dec 12, 2014 at 23:08
  • You don't want that data=[] as a default argument, as iCodez writes below. What you want is data=None, then in the body of the __init__ you can write if data is None: self.data = [] or whatever you had planned to do with it. Commented Dec 12, 2014 at 23:13

2 Answers 2

6

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

Sign up to request clarification or add additional context in comments.

2 Comments

you should never have a mutable object such as a list as a default argument - not necessarily never - but 99% of the time, it's definitely not what you want and is going to bite you.
There, I used "almost never". :-)
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.