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浅复制与深复制