[Tutor] multiple class instances

Arne Mueller a.mueller@icrf.icnet.uk
Mon, 10 May 1999 20:44:12 +0100


Hi All -

and thanks Corran for the that 'beautyful' help. I mean it wasn't that
abstract as your last article - so was able to get most of it ;-).
Realy, thank very much!

> Which leads to the infamous default method gotcha:
> 
> class Bla:
>   def __init__(self, mylist = []):
>     self.mylist = mylist
> 
> (note: can be any method, not just __init__)
>
> For the tutees: the default argument [] is actually an anonymous class
> variable - so this construct means that for each instance the variable
> x.mylist refers to the same mutable object
> 
> >>> x = Bla()
> >>> y = Bla()
> >>> print y.mylist
> []
> >>> x.mylist.append('a')
> >>> print y.mylist
> ['a']
> 
> Everyone gets bitten by this at least once.  A good idiom to do what
> you _want_ to do in this case is:
> 
> class Bla:
>   def __init__(self, mylist = None):
>     self.mylist = mylist or []
> 

But z = Bla(['my_own']) get's it's own list object (not only reference).
>From this point on it's sort of independent ... (right).

Do I have to know that the empty list '[]' in the above example is an
anonymous class variable (of class 'list'?) because it's following the
python philosophy or do you know that because you had a look in the
implementation of python's list class?

So python programmers have to be aware of class variables (especially
when they're anonymous). Huh, that's realy hard to get but I think it'll
become better when writing some python progs :-) .

        Thanks,

        Arne