gpt4 book ai didi

python - python 中的可变默认值

转载 作者:行者123 更新时间:2023-12-01 05:34:13 25 4
gpt4 key购买 nike

class Foo:
def __init__(self, stuff = []):
print(stuff)
self.stuff = stuff
def add(self,x):
self.stuff.append(x)


>>>f = Foo()
[]
>>>f.add(1)
>>>g = Foo()
[1]

我只对代码做了一处更改(第 4 行)

class Foo:
def __init__(self, stuff = []):
print(stuff)
self.stuff = stuff or []
def add(self,x):
self.stuff.append(x)


>>>f = Foo()
[]
>>>f.add(1)
>>>g = Foo()
[]

我更改了第 4 行中的某些内容,但导致打印结果发生变化(位于第 3 行中)

我只是想知道它是如何工作的。

最佳答案

作为后备参数值传递的列表会实例化一次,并在每次调用 __init__ 时重复使用。因此,向其中添加一个值将传播到 Foo 的每个下一个实例。

第一个和第二个示例之间的区别是 stuff 或 []。您需要知道列表在计算为 bool 值时为False,因此stuff或[]表达式返回第二个操作数如果 stuff 为空,在您的示例中始终是这种情况。第二个操作数是在方法调用中实例化的列表,因此每次调用 __init__ 时都会有一个不同的实例。这确保了附加值不会传播。

关于python - python 中的可变默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19483471/

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