我刚接触Python (而且对编程了解不多),但我记得我读过一篇文章,说python通常不复制值,所以任何a =b语句都会使b指向a。
a = 1
b = a
a = 2
print(b)给出结果1。这不应该是2吗?
发布于 2012-07-27 22:52:23
不,结果应该是1。
将赋值运算符( = )视为引用的赋值。
a = 1 #a references the integer object 1
b = a #b and a reference the same object
a = 2 #a now references a new object (2)
print b # prints 1 because you changed what a references, not b在处理像lists这样的可变对象而不是像int、float和tuple这样的不可变对象时,整个区别是最重要的。
现在考虑以下代码:
a=[] #a references a mutable object
b=a #b references the same mutable object
b.append(1) #change b a little bit
print a # [1] -- because a and b still reference the same object
# which was changed via b.发布于 2012-07-27 22:54:13
当您执行b = a时,它会使b引用与a相同的值。然后,当您执行a = 2时,它会引用一个新值。B不受影响。
Python中的赋值规则:
发布于 2012-07-27 22:58:31
@mgilson有一个很棒的answer,但我发现它有点难以理解。我把这个答案放进去,试图用一种不同的方式来解释它。
a = 1 # This makes a point to a location in memory where the Integer(1) is located
b = a # This makes b point to the same place.
a = 2 # This makes a point to a different location in memory where Integer(2) is located
print(b) # b still points to the place where Integer(1) was stored, so it prints out 1.https://stackoverflow.com/questions/11690220
复制相似问题