python byRef //复制


问题内容

我是Python新手(无论如何也不了解编程知识),但我记得读过python通常不会复制值,因此任何语句a = b会使b指向a。如果我跑步

a = 1
b = a
a = 2
print(b)

给出结果1.应该不是2吗?


问题答案:

不,结果应为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,而不是 一成不变的 状物体intfloattuple

现在考虑以下代码:

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.