gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 07:46:20 26 4
gpt4 key购买 nike

<分区>

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

我显然在这里遗漏了一些东西:谁能解释为什么 t1“神秘地”获得 t2self.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']

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com