在python中,对象赋值实际上是对象的引用,当原始的对象的值改变,引用变量的值也改变(对数字的赋值不成立),类似c++中的引用,当变量值改变,这个变量的引用变量也改变。
1. 值赋 传递对象的引用,当原始对象改变,被赋值的b也会做相应的改变
In [1]: a = [1,2]
In [2]: b = a
In [3]: b
Out[3]: [1, 2]
In [4]: id(a)
Out[4]: 140111875030264
In [5]: id(b)
Out[5]: 140111875030264
In [6]: a.append(3)
In [7]: b
Out[7]: [1, 2, 3]
In [8]: id(b)
Out[8]: 140111875030264
2.浅拷贝 没有拷贝子对象,所以原始对象的子对象改变,b对象的子对象也会改变
In [3]: b = copy.copy(a)
In [4]: b
Out[4]: [1, 2, [3, 4]]
In [5]: id(a)
Out[5]: 139736780542896
In [6]:
In [6]: id(b)
Out[6]: 139736780545920
In [7]: a.append(5)
In [8]: a
Out[8]: [1, 2, [3, 4], 5]
In [9]: b
Out[9]: [1, 2, [3, 4]]
In [3]: b = copy.copy(a)
In [4]: b
Out[4]: [1, 2, [3, 4]]
In [5]: id(a)
Out[5]: 139736780542896
In [6]:
In [6]: id(b)
Out[6]: 139736780545920
In [7]: a.append(5)
In [8]: a
Out[8]: [1, 2, [3, 4], 5]
In [9]: b
Out[9]: [1, 2, [3, 4]]
In [3]: b = copy.copy(a)
In [4]: b
Out[4]: [1, 2, [3, 4]]
In [5]: id(a)
Out[5]: 139736780542896
In [6]:
In [6]: id(b)
Out[6]: 139736780545920
In [7]: a.append(5)
In [8]: a
Out[8]: [1, 2, [3, 4], 5]
In [9]: b
Out[9]: [1, 2, [3, 4]]
In [10]: a[2].append(6)
In [11]: a
Out[11]: [1, 2, [3, 4, 6], 5]
In [12]: b
Out[12]: [1, 2, [3, 4, 6]]
3.深拷贝 原始对象a的任何改变变量c都不会改变
import copy
c = copy.deepcopy(a)