Shallow copy and deep copy of copy module
The copy module is used for copying operations on objects. The module provides only two main methods: Copy.copy and Copy.deepcopy, respectively, representing shallow and deep copy.
Direct assignment, the difference between a deep copy and a shallow copy
Direct assignment: Simply copy the object's reference, and the ID of the two object is the same. Is the object's reference (alias), which is to add a "label" to the current in-memory object. By using the built-in function ID (), you can see pointing to the same object in memory.
Shallow copy (copy): Copies the parent object and does not copy the inner sub-object of the object. That is, shallow copy copies only the object itself, not the object that the object refers to. A shallow copy constructs a new compound object and then, to the extentpossible, inserts references into It to the objects found in the original.
Deep Copy (deepcopy): The Deepcopy method of the Copy module, which completely copies the parent object and its child objects. That is, a new composite object is created, and all child objects are copied recursively, and the new composite object has no association with the original object. Although immutable sub-objects are actually shared, they do not affect their mutual independence. A deep copy constructs a new compound object and then, recursively, insertscopies to it of the objects found in the orig Inal.
The difference between a shallow copy and a deep copy is simply that for a composite object, the so-called composite object is an object that contains other objects, such as lists, class instances. In the case of numbers, strings, and other "atomic" types, there is no copy of the original object's reference, so the two are the same result.
ImportCopya= [1, [1, 2, 3]]b= A#Direct Copyc = Copy.copy (a)#Shallow CopyD = Copy.deepcopy (a)#Deep CopyA[0]= 2a[1][0] = 2Print('a', a)Print('b', B)Print('C', c)Print('D', d)
Log
A [2, [2, 2, 3]]b [2, [2, 2, 3]]c [1, [2, 2, 3]]d [1, [1, 2, 3]]
Python module-copy