copy.copy()中如果拷贝的是列表等可修改对象,则会拷贝最上一层,如果拷贝的最上层是元组等不可修改对象,则只是拷贝了对象的引用:
In [2]: a = [1, 2, 3]
In [3]: b = copy.copy(a)
In [4]: id(a)
Out[4]: 140568059574600
In [5]: id(b)
Out[5]: 140568059649992
In [6]: a = (1, 2, 3)
In [7]: b = copy.copy(a)
In [8]: id(a)
Out[8]: 140568101534096
In [9]: id(b)
Out[9]: 140568101534096
copy.deepcopy()中如果拷贝的是不可变对象,依然是拷贝对象的引用:
In [2]: a = (1, 2, 3)
In [3]: b = copy.deepcopy(a)
In [4]: id(a)
Out[4]: 140313481712336
In [5]: id(b)
Out[5]: 140313481712336
而如果嵌套内部包含可修改和不可修改对象,则会逐级拷贝所有的可修改对象并只拷贝所有的不可修改对象的引用:
In [6]: a = [1, 3]
In [7]: b = (2, 4)
In [8]: c = [a, b]
In [9]: d = copy.deepcopy(c)
In [10]: id(c)
Out[10]: 140313510332424
In [11]: id(d)
Out[11]: 140313468881672
In [12]: id(c[1])
Out[12]: 140313468353096
In [13]: id(d[1])
Out[13]: 140313468353096
In [14]: id(c[0])
Out[14]: 140313468365640
In [15]: id(d[0])
Out[15]: 140313468161608
如果内层包含有可修改对象,则无论外层为可修改对象还是不可修改对象,对外层对象都会进行拷贝,而不是仅对外层对象的引用进行拷贝:
In [16]: a = [1, 3]
In [17]: b = (2, 4)
In [18]: c = (a, b)
In [19]: d = copy.deepcopy(c)
In [20]: id(c)
Out[20]: 140313510401352
In [21]: id(d)
Out[21]: 140313482148872
In [22]: id(c[0])
Out[22]: 140313482149192
In [23]: id(d[0])
Out[23]: 140313468180744
In [24]: id(c[1])
Out[24]: 140313479821256
In [25]: id(d[1])
Out[25]: 140313479821256
In [26]: e = (c, (1, 3))
In [27]: f = copy.deepcopy(e)
In [28]: id(e)
Out[28]: 140313510249160
In [29]: id(f)
Out[29]: 140313468328072
In [30]: id(e[0])
Out[30]: 140313510401352
In [31]: id(f[0])
Out[31]: 140313479822280
In [32]: id(e[1])
Out[32]: 140313510370888
In [33]: id(f[1])
Out[33]: 140313510370888
切片也是浅拷贝的一种:
In [42]: a = (1, 3, 5)
In [43]: b = a[:]
In [44]: id(a)
Out[44]: 140313506521160
In [45]: id(b)
Out[45]: 140313506521160
In [46]: a = [1, 3, 5]
In [47]: b = a[:]
In [48]: id(a)
Out[48]: 140313468221256
In [49]: id(b)
Out[49]: 140313479813576
In [50]: id(a[0])
Out[50]: 10914496
In [51]: id(b[0])
Out[51]: 10914496
In [52]: a = [1, 3, [2, 4]]
In [53]: b = a[:]
In [54]: id(a)
Out[54]: 140313510367816
In [55]: id(b)
Out[55]: 140313468221256
In [56]: id(a[2])
Out[56]: 140313479811016
In [57]: id(b[2])
Out[57]: 140313479811016