python淺復制與深復制
In python, the assignment operator does not copy the objects, instead, they create bindings between an object and the target. The object, if a collection that is mutable or consists of mutable items uses the copy so that one can change one copy without changing the other.
在python中,賦值運算符不復制對象,而是在對象和目標之間創建綁定。 如果該對象是可變的或由可變項組成的集合,則使用該副本,以便一個副本可以更改一個副本而無需更改另一個副本。
The module copy provides generic shallow and deep copy operations,
模塊復制提供通用的淺層復制和深層復制操作 ,
淺拷貝 (Shallow Copy)
A shallow copy constructs a new compound object and then inserts references into it to the objects found in the original. This process is not recursive and hence doesn't create copies of the child object. In shallow copy, a reference of object is copied to another object, meaning any changes made to the copy of the object shall reflect on the original object too.
淺表副本將構造一個新的復合對象,然后將對原始對象中找到的對象的引用插入其中。 此過程不是遞歸的,因此不會創建子對象的副本。 在淺表復制中,將對象的引用復制到另一個對象,這意味著對對象副本所做的任何更改也應反映在原始對象上。
copy.copy(x) # returns shallow copy
Example:
例:
-bash-4.2$ python3
Python 3.6.8 (default, Apr 25 2019, 21:02:35)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-36)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import copy
>>> xs = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> ys = copy.copy(xs)
>>> print(xs)
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> print(ys)
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> xs.append(['new sublist']) # Modifying the copied list at a "superficial" level was no problem at all.
>>> print(xs)
[[1, 2, 3], [4, 5, 6], [7, 8, 9], ['test']]
>>> print(ys)
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> xs[1][0] = 'X1' // changes both 'xs' and 'ys'
>>> print(xs)
[[1, 2, 3], ['X1', 5, 6], [7, 8, 9], ['test']]
>>> print(ys)
[[1, 2, 3], ['X1', 5, 6], [7, 8, 9]]
深拷貝 (Deep Copy)
A deep copy constructs a new compound object and then recursively inserts the copies into it the objects found in the original.
深層副本會構造一個新的復合對象,然后將原始對象中找到的對象遞歸地插入副本。
copy.deepcopy(x) # returns a deep copy
Example:
例:
-bash-4.2$ python3
Python 3.6.8 (default, Apr 25 2019, 21:02:35)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-36)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import copy
>>> ys = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> zs = copy.deepcopy(ys)
>>> ys[1][1] = 'X'
>>> print(ys)
[[1, 2, 3], [4, 'X', 6], [7, 8, 9]]
>>> print(zs)
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>>
重要提醒 (Important reminders)
Shallow copying of an object will not clone the child objects. Hence, the child copy is not fully independent of the parent.
淺復制對象不會克隆子對象。 因此,子副本并不完全獨立于父副本。
A deep copy of an object will recursively clone the child object and hence the child object is fully independent of the parent. Creating a deep copy is slower.
對象的深層副本將遞歸克隆子對象,因此子對象完全獨立于父對象。 創建深層副本比較慢。
An arbitrary object, including custom classes, can be copied using the copy module.
可以使用復制模塊復制包括定制類在內的任意對象。
翻譯自: https://www.includehelp.com/python/shallow-copy-vs-deep-copy.aspx
python淺復制與深復制