浅拷贝
- 类似于对于引用的拷贝
In [1]: a = [11,22,33]
In [2]: b = [44,55,66]
In [3]: c = [a,b]
In [4]: c
Out[4]: [[11, 22, 33], [44, 55, 66]]
In [5]: d = c
In [6]: d
Out[6]: [[11, 22, 33], [44, 55, 66]]
In [7]: c
Out[7]: [[11, 22, 33], [44, 55, 66]]
In [8]: id(d)
Out[8]: 4366797352
In [9]: id(c)
Out[9]: 4366797352
In [10]: c[0].append(44)
In [11]: c
Out[11]: [[11, 22, 33, 44], [44, 55, 66]]
In [12]: d
Out[12]: [[11, 22, 33, 44], [44, 55, 66]]
In [13]: id(c)
Out[13]: 4366797352
In [14]: id(d)
Out[14]: 4366797352
深拷贝
- 完全拷贝了一个副本
In [1]: import copy
In [2]: a = [11,22,33]
In [3]: b = [33,44,55]
In [4]: c = [a,b]
In [5]: e = copy.deepcopy(c)
In [6]: c
Out[6]: [[11, 22, 33], [33, 44, 55]]
In [7]: e
Out[7]: [[11, 22, 33], [33, 44, 55]]
In [8]: id(c)
Out[8]: 4431089464
In [9]: id(e)
Out[9]: 4429576528
In [10]: c[0].append(44)
In [11]: c
Out[11]: [[11, 22, 33, 44], [33, 44, 55]]
In [12]: e
Out[12]: [[11, 22, 33], [33, 44, 55]]
In [13]: id(c)
Out[13]: 4431089464
In [14]: id(e)
Out[14]: 4429576528
其他浅拷贝,如:copy.copy
- 特别要主要拷贝的对象是可变类型还是不可变类型
不可变类型
In [1]: import copy
In [2]: a = (11,22,33,[44,55])
In [3]: b = copy.copy(a)
In [4]: a
Out[4]: (11, 22, 33, [44, 55])
In [5]: b
Out[5]: (11, 22, 33, [44, 55])
In [6]: id(a)
Out[6]: 4427232456
In [7]: id(b)
Out[7]: 4427232456
In [8]: a[3].append(66)
In [9]: a
Out[9]: (11, 22, 33, [44, 55, 66])
In [10]: b
Out[10]: (11, 22, 33, [44, 55, 66])
In [11]: id(a)
Out[11]: 4427232456
In [12]: id(b)
Out[12]: 4427232456
In [13]: id(a[3])
Out[13]: 4427525224
In [14]: id(b[3])
Out[14]: 4427525224
可变类型
In [1]: import copy
In [2]: a = [11,22,33,(44,55)]
In [3]: b = copy.copy(a)
In [4]: a
Out[4]: [11, 22, 33, (44, 55)]
In [5]: b
Out[5]: [11, 22, 33, (44, 55)]
In [6]: id(a)
Out[6]: 4337742480
In [7]: id(b)
Out[7]: 4336618168
In [8]: a.append(66)
In [9]: a
Out[9]: [11, 22, 33, (44, 55), 66]
In [10]: b
Out[10]: [11, 22, 33, (44, 55)]
In [11]: id(a)
Out[11]: 4337742480
In [12]: id(b)
Out[12]: 4336618168
copy.copy针对copy的对象是否是可变类型会不一样,如果拷贝的是可变类型,那么重新再内存中开辟地址,并将值拷贝过去;如果是不可变类型,那么只会拷贝一份引用,但是如果不可变类型中还有可变类型,如:(11,22,33,[44,55]),在[44,55]中append值,两个对象的值都会变,因为他们指向的是同一份引用