骄傲的赛亚人

浅拷贝和深拷贝的区别

  • 浅拷贝(copy):拷贝父对象,不会拷贝对象的内部的子对象。

  • 深拷贝(deepcopy): copy 模块的 deepcopy 方法,完全拷贝了父对象及其子对象。

dict1={"name":"匡","age":26,"money":99999,"height":[10,20,30]}
dict2=dict1.copy()
dict1["height"].remove(10)
print(dict1)
print(dict2)

输出:

{'name': '匡', 'age': 26, 'money': 99999, 'height': [20, 30]}
{'name': '匡', 'age': 26, 'money': 99999, 'height': [20, 30]}

浅拷贝:复制后对原始对象进行删除时,被复制的对象也会同步删除

 

import copy
dict1={"name":"匡","age":26,"money":99999,"height":[10,20,30]}
dict2=copy.deepcopy(dict1)
dict1["height"].remove(10)
print(dict1)
print(dict2)

输出:

{'name': '匡', 'age': 26, 'money': 99999, 'height': [20, 30]}
{'name': '匡', 'age': 26, 'money': 99999, 'height': [10, 20, 30]}

深拷贝:复制后,对原始对象进行操作,不会影响复制后的对象

https://www.runoob.com/w3cnote/python-understanding-dict-copy-shallow-or-deep.html 

 

posted on 2021-02-18 15:56  骄傲的赛亚人  阅读(58)  评论(0编辑  收藏  举报

导航