Possible Duplicate:
“Least Astonishment” in Python: The Mutable Default Argument
I'm obviously missing something here: can anyone explain why t1
"mysteriously" acquires the self.thelist
value of t2
? What am I doing wrong?
>>> class ThingyWithAList(object):
... def __init__(self, alist=[]):
... super(ThingyWithAList, self).__init__()
... self.thelist = alist
...
>>> t1 = ThingyWithAList()
>>> t1.thelist.append('foo')
>>> t1.thelist.append('bar')
>>> print t1, t1.thelist
<__main__.ThingyWithAList object at 0x1004a8350> ['foo', 'bar']
>>>
>>> t2 = ThingyWithAList()
>>> print t2, t2.thelist
<__main__.ThingyWithAList object at 0x1004a8210> ['foo', 'bar']