Skip to main content
 首页 » 编程设计

Python之使用具有空列表默认值的命名构造函数参数时的意外行为

2025年05月04日15arxive

<分区>

Possible Duplicate:
“Least Astonishment” in Python: The Mutable Default Argument

我显然在这里遗漏了一些东西:谁能解释为什么 t1“神秘地”获得 t2 的 self.thelist 值?我做错了什么?

>>> 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']