[Tutor] Default list arguments in __init__
Moos Heintzen
iwasroot at gmail.com
Sat Feb 21 20:38:49 CET 2009
Hi,
This behavior was totally unexpected. I only caught it because it was
the only thing I changed.
>>> class foo:
... def __init__(self, lst=[]):
... self.items = lst
...
>>> f1 = foo()
>>> f1.items
[]
>>> f1.items.append(1)
>>> f2 = foo()
>>> f2.items
[1]
Huh? lst is a reference to the *same list* every instance?
I guess I have to do it like this. It seems to work. (i.e. every foo
instance with default lst now has a unique new list.)
def__init__(self, lst=None):
self.items = lst or []
This is on python 2.4.4c1
More information about the Tutor
mailing list