问题描述
列表,x
,不会在每次函数操作时初始化为参数默认值,而是保持之前的状态并添加一个新值。
这就是函数被执行 5 次的方式,所以它变成了 [7,7,7]
。
但是,整数 y 似乎保持默认值。它已经运行了 5 次,但它继续输出 2
。
函数执行5次时,为什么y
最终输出的是2
而不是6
?
我已经阅读了 this question,但它解释了列表绑定到函数的位置。但是我想知道为什么这个原则不适用于整数默认参数。
def foo(x=[],y=1):
x.append(7)
y += 1
return x,y
print(foo())
print(foo())
print(foo())
print(foo())
print(foo())
([7],2)
([7,7],2)
解决方法
Int 是不可变的,列表不是。当您为参数分配默认值时,您正在分配对该值的引用。执行 y += 1
实际上会创建一个新引用并将其分配给 y
,它不会更改旧引用的值。当你改变容器时,你不会改变引用。示例:
y = 1
x = y
# This will be true as they have the same reference
print(x is y) # True
y += 1
# This will be false as the reference to y has been changed
print(x is y) # False
y = []
x = y
# This will be true as they have the same reference
print(x is y) # True
y.append(1)
# This will still be true,the reference to the container remains the same.
print(x is y) # True