Python-copy与deepcopy(浅拷贝/深拷贝)区别

时间:2022-04-17 19:48:55

我们日常理解的copy等于“将对象内容拷贝出来,成立了一个新的对象”

这也是copy与赋值的区别

1.对于非复杂对象 list = [1,2,3,4]

copy = deepcopy

In [1]: import copy
In [2]: list = [1,2,3,4]
In [3]: list1 = list
In [4]: list2 = copy.copy(list)
In [5]: list3 = copy.deepcopy(list)
####对于非复杂对象 list = [1,2,3,4]
####copy = deepcopy
In [6]: id(list)
Out[6]: 140138558856392
In [7]: id(list1)
Out[7]: 140138558856392
In [8]: id(list2)
Out[8]: 140138558911496
In [9]: id(list3)
Out[9]: 140138558842056
####对于非复杂对象 list = [1,2,3,4]
####copy = deepcopy
In [10]: list[0] = "A"
In [11]: list
Out[11]: ['A', 2, 3, 4]
In [12]: list1
Out[12]: ['A', 2, 3, 4]
In [13]: list2
Out[13]: [1, 2, 3, 4]
In [14]: list3
Out[14]: [1, 2, 3, 4]
####对于非复杂对象 list = [1,2,3,4]
####copy = deepcopy
In [15]: id(list)
Out[15]: 140138558856392
In [16]: id(list1)
Out[16]: 140138558856392
In [17]: id(list2)
Out[17]: 140138558911496
In [18]: id(list3)
Out[18]: 140138558842056

2.对于复杂对象(嵌套)list =[1,2,3,[4,5,6]]

copy只能copy主对象,对于子对象copy等同于赋值(或理解为引用)

In [1]: import copy
In [2]: list = [1,2,3,[4,5,6]]
In [3]: list1 = list
In [4]: list2 = copy.copy(list)
In [5]: list3 = copy.deepcopy(list)
###对于复杂对象(嵌套) list =[1,2,3,[4,5,6]]
###copy只能copy主对象,对于子对象的copy等同于赋值(或理解为引用)
In [6]: id(list)
Out[6]: 140326361517320
In [7]: id(list1)
Out[7]: 140326361517320
In [8]: id(list2)
Out[8]: 140326376997256
In [9]: id(list3)
Out[9]: 140326361507144
###对于复杂对象(嵌套) list =[1,2,3,[4,5,6]]
###copy只能copy主对象,对于子对象的copy等同于赋值(或理解为引用)
In [10]: list[3][1] = "B"
In [11]: list
Out[11]: [1, 2, 3, [4, 'B', 6]]
In [12]: list1
Out[12]: [1, 2, 3, [4, 'B', 6]]
In [13]: list2
Out[13]: [1, 2, 3, [4, 'B', 6]]
In [14]: list3
Out[14]: [1, 2, 3, [4, 5, 6]]
###对于复杂对象(嵌套) list =[1,2,3,[4,5,6]]
###copy只能copy主对象,对于子对象的copy等同于赋值(或理解为引用)
In [15]: id(list)
Out[15]: 140326361517320
In [16]: id(list1)
Out[16]: 140326361517320
In [17]: id(list2)
Out[17]: 140326376997256
In [18]: id(list3)
Out[18]: 140326361507144