[Tutor] Default parameter in class method

Alan Gauld alan.gauld at btinternet.com
Tue Oct 7 17:29:14 CEST 2008


"Daniele" <d.conca at gmail.com> wrote

> I want to create a method of a class with a default value. The 
> problem
> is that this default value should be an instance field of that same
> class. For example:
>
> class Test():
>  def __init__(self):
>    self.field='Default'
>
>  def myMethod(self, parameter=self.field):
>    pass


This has little to do with OOP per se.
You cannot make a default value of a normal function refer to a
dynamic variable. It has to be a constant value (or the current
value of a variable at the time the function is defined).

Consider:

>>> myvar = None
>>> def f1():
...   global myvar
...   myvar = 42
...
>>> def f2(n = myvar):
...   print n
...
>>> myvar
None
>>> f2()
None
>>> f1()   # set myvar to 42
>>> myvar
42
>>> f2()   # still using the original myvar value
None
>>> myvar
42
>>>

So the default value is bound to the value of myvar
at the time the function was defined. Even if myvar
changes the default value will not.

So in the OOP case binding to a field value won't
work because the field doesn't get defined until
an object is instantiated but the class definition
(including the method) will be executed before
any instances are created.

Kent has shown how to use a default binding to
None to do what you want. I just wanted to point
out that the same issues arise using functions.

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 




More information about the Tutor mailing list