当函数多次运行时,列表嵌套在默认参数中,但整数不是

问题描述

列表,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

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...