我试图了解 Python 的变量范围方法。在这个例子中,为什么 f()
能够改变 x
的值,正如在 main()
中所感知的那样,但不能改变n
?
def f(n, x):
n = 2
x.append(4)
print('In f():', n, x)
def main():
n = 1
x = [0,1,2,3]
print('Before:', n, x)
f(n, x)
print('After: ', n, x)
main()
输出:
Before: 1 [0, 1, 2, 3]
In f(): 2 [0, 1, 2, 3, 4]
After: 1 [0, 1, 2, 3, 4]
最佳答案
有些答案在函数调用的上下文中包含“复制”一词。我觉得很困惑。
Python 不会复制您在函数调用期间传递的对象永远。
函数参数是名称。当您调用函数时,Python 会将这些参数绑定(bind)到您传递的任何对象(通过调用者范围内的名称)。
对象可以是可变的(如列表)或不可变的(如 Python 中的整数和字符串)。您可以更改的可变对象。您无法更改名称,只能将其绑定(bind)到另一个对象。
您的示例与 scopes or namespaces 无关, 大约是 naming and binding和 mutability of an object在 Python 中。
def f(n, x): # these `n`, `x` have nothing to do with `n` and `x` from main()
n = 2 # put `n` label on `2` balloon
x.append(4) # call `append` method of whatever object `x` is referring to.
print('In f():', n, x)
x = [] # put `x` label on `[]` ballon
# x = [] has no effect on the original list that is passed into the function
the difference between variables in other languages and names in Python 上的图片不错.
https://stackoverflow.com/questions/575196/