Possible Duplicate:
“Least Astonishment” in Python: The Mutable Default Argument
I have something quite strange when I tried to write a class like below. On the line 3, I must put a new copy of the argument newdata to the self.data, otherwise, it seems that when I initiate a new class instance, the value of the previous one is still remembered by the class. see the example below and please pay attention to the only difference in the two versions of code on line 3.
class Pt(object):
def __init__(self,newdata={}):
self.data=newdata.copy()
if self.data == {}:
self._taglist = []
else:
self._taglist = self.data.keys()
def add_tag(self,tag=None):
self.data[tag]={'x':[0,1,2,3,4]}
self._taglist.append(tag)
In [49]: pt = Pt()
In [50]: pt.add_tag('b')
In [51]: pt.add_tag('a')
In [52]: pt.data
Out[52]: {'a': {'x': [0, 1, 2, 3, 4]}, 'b': {'x': [0, 1, 2, 3, 4]}}
In [53]: pt2 = Pt()
In [54]: pt2._taglist
Out[54]: []
class Pt(object):
def __init__(self,newdata={}):
self.data=newdata
if self.data == {}:
self._taglist = []
else:
self._taglist = self.data.keys()
def add_tag(self,tag=None):
self.data[tag]={'x':[0,1,2,3,4]}
self._taglist.append(tag)
In [56]: pt = Pt()
In [57]: pt.add_tag('a')
In [58]: pt.add_tag('b')
In [59]: pt._taglist
Out[59]: ['a', 'b']
In [60]: pt2 = Pt()
In [61]: pt2._taglist
Out[61]: ['a', 'b']
In [62]: pt2.data
Out[62]: {'a': {'x': [0, 1, 2, 3, 4]}, 'b': {'x': [0, 1, 2, 3, 4]}}
I guess the second case happens because: both newdata and self.data refer to the same object (but how could this happen, the value should be given from right to the left but not reverse), so when I use the "add_tag" method to update the self.data, the newdata is updated as well. Yet I think when I initiate a new instance by pt2 = Pt(), the newdata should use the default value ({}), can it still keeps the old value from pt1?