欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

python关于深浅拷贝

程序员文章站 2024-01-17 22:07:22
...

#1.copy模块

方法:
(1)copy.copy(x)
Return a shallow copy of x.
(2)copy.deepcopy(x)
Return a deep copy of x.
(3)exception copy.error
Raised for module specific errors.

#2.shallow copy 和deep copy

The difference between shallow and deep copying is only relevant for compound objects (objects that contain other objects, like lists or class instances):
•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.

shallow copy只是复制对象的引用,并不复制对象本身;而deep copy完全复制一份源文件(深浅拷贝的区别只适用于混合对象的拷贝)

深拷贝存在的问题:Two problems often exist with deep copy operations that don’t exist with shallow copy operations:
•Recursive objects (compound objects that, directly or indirectly, contain a reference to themselves) may cause a recursive loop.
•Because deep copy copies everything it may copy too much, such as data which is intended to be shared between copies.
解决方案:
The deepcopy() function avoids these problems by:
•keeping a “memo” dictionary of objects already copied during the current copying pass; and
•letting user-defined classes override the copying operation or the set of components copied.

下例:浅拷贝

a=[1,2,3,[4,5,6],7,8]
b=a.copy()
c=a
a[1]='sb'
a[3][1]='shit'
print(a, b, c, sep='\n')
#result
[1, 'sb', 3, [4, 'shit', 6], 7, 8]
[1, 2, 3, [4, 'shit', 6], 7, 8]
[1, 'sb', 3, [4, 'shit',6], 7, 8]
相关标签: python copy