围绕这个“问题”似乎有很多困惑。Python中的变量名实际上都是对对象的引用。对变量名的赋值实际上并没有改变对象本身,而是将引用设置为新对象。所以在你的情况下:
foo = 1 #
def test(bar):
# At this point, "bar" points to the same object as foo.
bar = 2 # We're updating the name "bar" to point an object "int(2)".
# 'foo' still points to its original object, "int(1)".
print foo, bar # Therefore we're showing two different things.
test(foo)
Python 的语法类似于 C 的方式以及许多东西都是语法糖的事实可能会令人困惑。记住整数对象实际上是不可变的,这foo += 1
可能是一个有效的陈述似乎很奇怪。实际上,foo += 1
实际上等价于foo = foo + 1
,两者都转换为foo = foo.__add__(1)
,它实际上返回一个新对象,如下所示:
>>> a = 1
>>> id (a)
18613048
>>> a += 1
>>> id(a)
18613024
>>>