Python中的深拷贝和浅拷贝
2018-03-13 本文已影响10人
菩灵
自学Python一个多月了,前一阵子听老师讲深拷贝浅拷贝的概念,一团浆糊,于是,查了很多资料,大概理清了些思路,对于深拷贝和浅拷贝有了初步理解。
import copy
a = [11,22,33,[1,2,3]]
b = a
c = copy.copy(a)
d = copy.deepcopy(a)
a.append(8)
a[3][0] = 10
print(b)
print(c)
print(d)
结果就是:
[11,22,33,[10,2,3],8]
[11,22,33,[10,2,3]]
[11,22,33,[1,2,3]]
赋值,就是传递对象引用(毁三观的拷贝方式)
浅拷贝,只拷贝父类,不拷贝子类(可能并不常用)
深拷贝,递归拷贝,完全复制一份新的(传统意义上的拷贝)
所以会有:
a = [1,2,3]
b = a
a == b
True
a is b
True
a = [5,6,7]
b仍然等于[1,2,3]
a[0] = 5
a[1] = 6
a[2] = 7
此时b才等于[5,6,7]
a = [11, 22, 33, [46, 2, 3], 89, 23, 0, 89]
b = a
c = a[:]
a.append(123)
a[3][2] = 5
a
[11, 22, 33, [46, 2, 5], 89, 23, 0, 89, 123]
b
[11, 22, 33, [46, 2, 5], 89, 23, 0, 89, 123]
c
[11, 22, 33, [46, 2, 5], 89, 23, 0, 89]
突然发现,c.copy(a)和c = a[:]是一样的效果