1. 程式人生 > >python關於深淺拷貝

python關於深淺拷貝

#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]