def func():
global x
print 'x is', x
x = 2
print id(x)
print 'Changed global x to', x
x = 50
print id(x)
func()
print 'Value of x is', x
print id(x)
输出蟒蛇身份全局变量
32308172
x is 50
32308748
Changed global x to 2
Value of x is 2
32308748
我期待id()
应该因为x
同一副本是全球使用的所有的所有三次返回相同的值。为什么它的行为如此。
整数是不变的,而'global'指**姓名**'x',没有任何潜在的对象恰好是分配给。看看例如http://nedbatchelder.com/text/names.html – jonrsharpe
它是对象的ID,而不是变量的ID。在CPython中尝试:'a = 1'' id(a)''b = 1'' id(b)' – Roberto
@Roberto,这个例子可能会给出令人困惑的结果,因为小整数是* interned *。 – jonrsharpe