# 2.4. 深拷贝和浅拷贝
**浅拷贝只拷贝了引用,并没有拷贝内容,相当于把原来的引用复制了一份给新的变量**
**深拷贝是将原来的值复制了一份到新的地方**
In [30]: a=[1,2,3]
In [31]: b=a
In [32]: id(a)
Out[32]: 140618626865352
In [33]: id(b)
Out[33]: 140618626865352
In [34]: import copy
In [35]: c = copy.d
copy.deepcopy copy.dispatch_table
In [35]: c = copy.deepcopy(a)
In [36]: id(c)
Out[36]: 140618627080392
In [37]: a=[1,2]
In [38]: a
Out[38]: [1, 2]
In [39]: b
Out[39]: [1, 2, 3]
In [40]: b=a
In [41]: a
Out[41]: [1, 2]
In [42]: b
Out[42]: [1, 2]
In [43]: a.append(4)
In [44]: a
Out[44]: [1, 2, 4]
In [45]: b
Out[45]: [1, 2, 4]
In [46]: c
Out[46]: [1, 2, 3]
### ```copy.deepcopy()```是递归的拷贝
In [47]: a=[1,2,3]
In [48]: b=[4,5,6]
In [49]: c=[a,b]
In [50]: d=copy.deepcopy(c)
In [51]: c
Out[51]: [[1, 2, 3], [4, 5, 6]]
In [52]: d
Out[52]: [[1, 2, 3], [4, 5, 6]]
In [53]: id(c)
Out[53]: 140618626186888
In [54]: id(d)
Out[54]: 140618627245000
In [55]: a.append(5)
In [56]: c
Out[56]: [[1, 2, 3, 5], [4, 5, 6]]
In [57]: d
Out[57]: [[1, 2, 3], [4, 5, 6]]
d是c的深拷贝,里面的内容也是深拷贝,是递归的拷贝
### ```copy.copy()```一层的深拷贝
In [58]: a=[1,2,3]
In [59]: b=[4,5,6]
In [60]: c=[a,b]
In [61]: d=copy.copy(c)
In [62]: c
Out[62]: [[1, 2, 3], [4, 5, 6]]
In [63]: d
Out[63]: [[1, 2, 3], [4, 5, 6]]
In [64]: id(c)
Out[64]: 140618627247048
In [65]: id(d)
Out[65]: 140618626985544
In [66]: a.append(5)
In [67]: c
Out[67]: [[1, 2, 3, 5], [4, 5, 6]]
In [68]: d
Out[68]: [[1, 2, 3, 5], [4, 5, 6]]
d只拷贝了一层,当a修改是,c和d都发生了改变
#### ```copy.copy()```在处理可变类型和不可变类型的时候结果不太一样
In [69]: a=[1,2,3]
In [70]: b=[4,5,6]
In [71]: c=(a,b)
In [72]: c
Out[72]: ([1, 2, 3], [4, 5, 6])
In [73]: d=copy.copy(c)
In [74]: id(c)
Out[74]: 140618626859272
In [75]: id(d)
Out[75]: 140618626859272
In [76]: e=copy.deepcopy(c)
In [77]: id(e)
Out[77]: 140618626853000
In [78]: a.append(5)
In [79]: c
Out[79]: ([1, 2, 3, 5], [4, 5, 6])
In [80]: d
Out[80]: ([1, 2, 3, 5], [4, 5, 6])
In [81]: e
Out[81]: ([1, 2, 3], [4, 5, 6])
d是c的copy.copy但是还是原来的id号,说明在处理不可变类型的时候,copy不是深拷贝