Variables in Python are references, or names, not like variables in C etc.
This code:
x=y=Queue()
means "allow the name y
to reference an object in memory made by calling Queue()
, and allow the name x
to reference the object that y
is pointing to." This means both variables refer to the same object - as you can verify with id(x) == id(y)
.
This code:
x=Queue()
y=Queue()
means "allow the name x
to reference one object made by Queue()
, and allow the name y
to reference another object made by Queue()
". In this case, id(x) == id(y)
is False
This can often bite you:
a = [1,2,3,4,5]
b = a
b.append(6)
print(a)
# [1,2,3,4,5,6] even though we didn't seem to do anything to a!
To get around this, do import copy; b = a.copy();
instead of b = a
.
However, this behaviour doesn't occur to immutable objects like integers:
a = 7
a += 1
This doesn't go to the object that a
is referencing and change it by adding one, instead it dereferences a
from the object 7, and references it to the object representing the previous value of a
+ 1 (that is to say, 8). This is unlike actions performed on mutable objects, like lists in the previous example - appending to a list does change the object that the variable is referencing.
So we can do this:
a = 7
b = a
a += 1
print(a)
# 8
print(b)
# 7
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…