default argument in method
Hans-Peter Jansen
hpj at urpla.net
Wed Dec 15 15:10:05 EST 2010
On Monday 13 December 2010, 18:14:27 Godson Gera wrote:
> On Sun, Dec 12, 2010 at 5:05 PM, ernest <nfdisco at gmail.com> wrote:
> > Hi,
> >
> > I'd like to have a reference to an instance attribute as
> > default argument in a method. It doesn't work because
> > "self" is not defined at the time the method signature is
> > evaluated. For example:
> >
> > class C(object):
> > def __init__(self):
> > self.foo = 5
> > def m(self, val=self.foo):
> > return val
> >
> > Raises NameError because 'self' is not defined.
>
> You can defined foo outside the __init__ and can access it inside
> methods using self.foo
>
> class C(object):
> foo=5
> def __init__(self):
> print self.foo
> def m(self,val=foo):
> return val
>
> class attributes can be accessed with out self before them in method
> signatures. However, becareful if you change the value of foo inside
> any method, the method signature will still hold on to old value.
Since this is a major pitfall, it might be worth mentioning, that
mutable default arguments are generally a bad idea, as the default
arguments are evaluated just once, hence e.g. using an empty list might
contain the items, that were appended in earlier calls of this method..
Code, that _relies_ on such behavior should be yanked instantaneous and
the producer of such code should be punished with coding APL¹ on a
dubeolsik hangul keyboard² for a year at least..
Pete
¹) Not, that APL is a bad language per se, but even one liners tend to
be rather cryptic for usual brains. Let's say it with Dijkstra:
"APL is a mistake, carried out through perfection..."
but given the second constraint, it's going to be a, hmm, challenge.
http://en.wikipedia.org/wiki/APL_(programming_language)
²) http://en.wikipedia.org/wiki/Keyboard_layout#Dubeolsik
More information about the Python-list
mailing list