variables of the class are not available as default values?

Chris Rebert clp2 at rebertia.com
Thu Aug 27 17:44:53 EDT 2009


On Thu, Aug 27, 2009 at 2:37 PM, seanacais<kccnospam at glenevin.com> wrote:
> I'm working on a program where I wish to define the default value of a
> method as a value that was set in __init__.  I get a compilation error
> saying that self is undefined.
>
> As always a code snippet helps :-)
>
> class foo:
>    def __init__(self, maxvalue):
>        self.maxvalue = maxvalue
>        self.value = 0
>
>    def put(self, value=self.maxvalue):
>        self.value = value
>
> So if I call foo.put() the value is set to maxvalue but maxvalue can
> be specified when I instantiate foo.

> python test.py
> Traceback (most recent call last):
>  File "test.py", line 1, in <module>
>    class foo:
>  File "test.py", line 6, in foo
>    def put(self, value=self.maxvalue):
> NameError: name 'self' is not defined

> Explanations and/or workarounds much appreciated.

Workaround:

class foo:
    def __init__(self, maxvalue):
        self.maxvalue = maxvalue
        self.value = 0

    def put(self, value=None):
        self.value = self.value if value is None else value

Explanation:

Default values are only evaluated once, when the class is defined,
thus "self" is not defined at that point since the class is still
being defined when the method definition is executed and thus there
can be no instances yet anyway.

Cheers,
Chris
--
http://blog.rebertia.com



More information about the Python-list mailing list