variables of the class are not available as default values?

Andre Engels andreengels at gmail.com
Thu Aug 27 17:49:42 EDT 2009


On Thu, Aug 27, 2009 at 11: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.
>
> Explanations and/or workarounds much appreciated.

Explanation: The default value is calculated at the time the function
is defined, not at the time it is called. And at that time there is no
instance for "self" to refer to.

Workaround:


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

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


-- 
André Engels, andreengels at gmail.com



More information about the Python-list mailing list