我编写了以下代码,以检查是否通过值或引用传递了整数。
foo = 1
def f(bar):
print id(foo) == id(bar)
bar += 1
print foo, bar
f(foo)
我得到的输出是
True
1, 2
从Python文档中,id(object)
返回对象的标识。在CPython实现中,这是对象在内存中的地址。由于函数主体中的第一个语句返回True
,这意味着foo
已通过引用传递,但是为什么打印最后一条语句1, 2
而不是2, 2
?
围绕这个“问题”似乎有很多困惑。实际上,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
>>>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句