我试图理解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]

请参见:如何通过引用传递变量?


当前回答

如果用完全不同的变量重写函数,并且我们对它们调用id,那么它就很好地说明了这一点。我一开始不明白这一点,读了jfs的帖子和很好的解释,所以我试着理解/说服自己:

def f(y, z):
    y = 2
    z.append(4)
    print ('In f():             ', id(y), id(z))

def main():
    n = 1
    x = [0,1,2,3]
    print ('Before in main:', n, x,id(n),id(x))
    f(n, x)
    print ('After in main:', n, x,id(n),id(x))

main()
Before in main: 1 [0, 1, 2, 3]   94635800628352 139808499830024
In f():                          94635800628384 139808499830024
After in main: 1 [0, 1, 2, 3, 4] 94635800628352 139808499830024

Z和x有相同的id。就像文章所说的那样,不同的标签对应相同的底层结构。

其他回答

我的一般理解是,任何对象变量(如列表或字典等)都可以通过其函数进行修改。我相信你不能做的是重新分配形参-即,在可调用函数中通过引用分配它。

这与许多其他语言是一致的。

运行下面的简短脚本,看看它是如何工作的:

def func1(x, l1):
    x = 5
    l1.append("nonsense")

y = 10
list1 = ["meaning"]
func1(y, list1)
print(y)
print(list1)

N是一个int(不可变),并且一个副本被传递给函数,因此在函数中您正在更改副本。

X是一个列表(可变),指针的副本被传递给函数,因此x.a pend(4)改变了列表的内容。然而,你在你的函数中说x =[0,1,2,3,4],你不会在main()中改变x的内容。

正如jouell所说。这是一个什么指向什么的问题,我想补充的是,这也是一个=做什么和.append方法做什么之间的区别的问题。

When you define n and x in main, you tell them to point at 2 objects, namely 1 and [1,2,3]. That is what = does : it tells what your variable should point to. When you call the function f(n,x), you tell two new local variables nf and xf to point at the same two objects as n and x. When you use "something"="anything_new", you change what "something" points to. When you use .append, you change the object itself. Somehow, even though you gave them the same names, n in the main() and the n in f() are not the same entity, they only originally point to the same object (same goes for x actually). A change to what one of them points to won't affect the other. However, if you instead make a change to the object itself, that will affect both variables as they both point to this same, now modified, object.

让我们在不定义新函数的情况下说明.append方法和=方法之间的区别:

比较

    m = [1,2,3]
    n = m   # this tells n to point at the same object as m does at the moment
    m = [1,2,3,4] # writing m = m + [4] would also do the same
    print('n = ', n,'m = ',m)

to

    m = [1,2,3]
    n = m
    m.append(4)
    print('n = ', n,'m = ',m)

在第一个代码中,它将打印n = [1,2,3] m =[1,2,3,4],因为在第三行,你没有改变对象[1,2,3],而是你告诉m指向一个新的,不同的对象(使用'='),而n仍然指向原始对象。

在第二段代码中,它将输出n = [1,2,3,4] m =[1,2,3,4]。这是因为在整个代码中m和n仍然指向同一个对象,但是您使用.append方法修改了对象本身(m所指向的对象)…注意,不管你在第三行写m.p append(4)还是n.p append(4),第二段代码的结果都是一样的。

一旦你理解了这一点,剩下的唯一困惑就是真正理解,正如我所说,f()函数中的n和x与main()中的n和x并不相同,它们只是在调用f()时最初指向同一个对象。

我将重命名变量以减少混乱。N -> nf或nmain。X -> xf或xmain:

def f(nf, xf):
    nf = 2
    xf.append(4)
    print 'In f():', nf, xf

def main():
    nmain = 1
    xmain = [0,1,2,3]
    print 'Before:', nmain, xmain
    f(nmain, xmain)
    print 'After: ', nmain, xmain

main()

当你调用函数f时,Python运行时生成一个xmain的副本并将其赋值给xf,类似地,将nmain的副本赋值给nf。

在n的情况下,复制的值是1。

对于x,复制的值不是文本列表[0,1,2,3]。它是对那个列表的参考。Xf和xmain都指向同一个列表,所以当你修改Xf时,你也在修改xmain。

然而,如果你要写这样的东西:

    xf = ["foo", "bar"]
    xf.append(4)

您会发现xmain没有改变。这是因为,在行xf = ["foo", "bar"]中,您更改了xf以指向一个新的列表。对这个新列表所做的任何更改都不会对xmain仍然指向的列表产生影响。

希望这能有所帮助。: -)

当你在函数中传递命令n = 2时,它会找到一个内存空间,并将其标记为2。但是如果你调用append方法,你基本上是在引用位置x(不管它的值是什么)并对它做一些操作。