variables of the class are not available as default values?
andreengels at gmail.com
Thu Aug 27 23:49:42 CEST 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.
def __init__(self, maxvalue):
self.maxvalue = maxvalue
self.value = 0
def put(self, value=None):
if value is None:
self.value = self.maxvalue
self.value = value
André Engels, andreengels at gmail.com
More information about the Python-list