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?

Ryan
  • 7,621
  • 5
  • 18
  • 31
  • Just use named arguments: "Thing(fname=f_name, imobj=im_obj)", everything else defaults. – swstephe Dec 12 '14 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. – jme Dec 12 '14 at 23:13

2 Answers2

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

Community
  • 1
  • 1
  • *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. – Jon Clements Dec 12 '14 at 23:15
  • There, I used "almost never". :-) –  Dec 12 '14 at 23:17
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.

fredtantini
  • 15,966
  • 8
  • 49
  • 55