Python多重分配和引用 [英] Python multiple assignment and references
问题描述
为什么多重赋值为int而不是列表或其他对象提供不同的引用?
Why does multiple assignment make distinct references for ints, but not lists or other objects?
>>> a = b = 1
>>> a += 1
>>> a is b
>>> False
>>> a = b = [1]
>>> a.append(1)
>>> a is b
>>> True
推荐答案
在int示例中,您首先将相同的对象分配给a
和b
,然后将a
重新分配给另一个对象(结果a+1
). a
现在引用了另一个对象.
In the int example, you first assign the same object to both a
and b
, but then reassign a
with another object (the result of a+1
). a
now refers to a different object.
在列表示例中,您为a
和b
分配了相同的对象,但是您并没有做任何更改. append
仅更改列表对象的内部状态,而不更改其标识.因此它们保持不变.
In the list example, you assign the same object to both a
and b
, but then you don't do anything to change that. append
only changes the interal state of the list object, not its identity. Thus they remain the same.
如果将a.append(1)
替换为a = a + [1]
,则会得到不同的对象,因为再次将新对象(a+[1]
的结果)分配给a
.
If you replace a.append(1)
with a = a + [1]
, you end up with different object, because, again, you assign a new object (the result of a+[1]
) to a
.
请注意,a+=[1]
的行为将有所不同,但这是一个完整的其他问题.
Note that a+=[1]
will behave differently, but that's a whole other question.
这篇关于Python多重分配和引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!