Python中的浅复制、深复制

时间:2022-08-23 13:04:13

参考 https://docs.python.org/3/library/copy.html?highlight=copy%20copy#copy.copy

Fluent Python第四部分第8章

A shallow copy constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in the original.
A deep copy constructs a new compound object and then, recursively, inserts copies into it of the objects found in the original.

Note:

  1. 直接赋值:其实就是对象的引用(别名)。
  2. 浅复制(shallow copy):copy模块的copy方法,复制父对象,不会复制对象的内部的子对象。
  3. 深复制(deepcopy): copy 模块的 deepcopy 方法,完全复制了父对象及其子对象。
    注意,浅复制和深复制都创建新的对象,所以id()返回的值不同。浅复制的元素使用原始元素的引用(地址),而深复制的元素重拥有新的地址(即深复制copy everything).
    深复制符合我们的认知,复制返回的对象就是一个完全独立的对象。

例子1. 浅复制

import copy
origin_dict = {
    1 : [1,2,3]
}
#浅复制可以引入copy模块或者compound objects自带的copy()
#shcp_didct = origin_dict.copy()
shcp_dict = copy.copy(origin_dict)

print(id(origin_dict))
print(id(shcp_dict))

print(origin_dict[1].append(555))

print(origin_dict)
print(shcp_dict)

Python中的浅复制、深复制

例子2. 深复制

#深复制必须引入copy模块
import copy
origin_dict = {
    1 : [1,2,3]
}

shcp_dict = copy.deepcopy(origin_dict)

print(id(origin_dict))
print(id(shcp_dict))

print(origin_dict[1].append(555))

print(origin_dict)
print(shcp_dict)

Python中的浅复制、深复制