Problems with self as default parameter
markus at kepler.ibp.de
markus at kepler.ibp.de
Thu Jul 19 09:59:38 EDT 2001
Joonas Paalasmaa <joonas at olen.to> writes:
> How can I use class members as default values.
> The code above raises an error.
>
> class Test:
> def __init__(self,s):
> self.default = s
> def printer(self, string = self.default):
> print string
[...]
> NameError: name 'self' is not defined
That's it: the default values are evaluated only once, at the time
when the function is defined. And then the value of self.default
(which belongs to the instance, not to the class) is not defined. A
common idiom to overcome this problem is:
def printer(self, string = None):
if string is None: string = self.default
print string
- Markus
More information about the Python-list
mailing list