The difference between shadowcopy and deepcopy in python
In python, it is common to need to copy specific objects, and you might encounter various bugs because understanding the difference between these three operations is key: assignment, shallow copy, and deep copy.
Assignment (=), shallow copy (copy), and deep copy (deepcopy) are relatively easy to distinguish regarding assignment vs. copying, but shallow copy and deep copy are harder to differentiate.
The assignment statement does not copy the object; it simply binds the variable to the object. Any change to one object will affect the other. Copying allows you to change one object without affecting the other.
The difference between shallow and deep copy is that shallow copy does not affect the other object when values change, but adding or deleting elements can affect it. Deep copy creates a completely independent object, and changes to one will not affect the other.
Below is a practical code example illustrating the differences among the three.
Code
from copy import deepcopy
dic1 = {'a': 2, 'b': 3, 'c': 4}
dic2=dic1
dic1["a"]=1
print(dic1)
#{'a': 1, 'b': 3, 'c': 4}
print(dic2)
#{'a': 1, 'b': 3, 'c': 4}
# Assignment statement: both are exactly the same, changing one changes both
dic1 = {'a': [1,2,3], 'b': 3, 'c': 4}
dic2 = dic1.copy()
dic1["a"] = [2,3,4]
print(dic1)
#{'a': [2, 3, 4], 'b': 3, 'c': 4}
print(dic2)
#{'a': [1, 2, 3], 'b': 3, 'c': 4}
### Changing the value does not affect the other object's value
dic1 = {'a': [1,2,3], 'b': 3, 'c': 4}
dic2 = dic1.copy()
dic1["a"].append(4)
print(dic1)
#{'a': [1, 2, 3, 4], 'b': 3, 'c': 4}
print(dic2)
#{'a': [1, 2, 3, 4], 'b': 3, 'c': 4}
### This shows shallow copy copies elements and references to sub-objects. If the sub-object is mutable, changes affect both objects. See https://docs.python.org/3/library/copy.html for reference.
dic1 = {'a': [1,2,3], 'b': 3, 'c': 4}
dic2 = deepcopy(dic1)
dic1["a"].append(4)
print(dic1)
#{'a': [1, 2, 3, 4], 'b': 3, 'c': 4}
print(dic2)
#{'a': [1, 2, 3], 'b': 3, 'c': 4}
Summary
In practical use, do not use assignment on callable objects as a copy method.
If the object does not have cyclic references or the data is not extremely large, using deep copy is safe.
- 原文作者:春江暮客
- 原文链接:https://www.bobobk.com/en/200.html
- 版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 4.0 国际许可协议进行许可,非商业转载请注明出处(作者,原文链接),商业转载请联系作者获得授权。