The difference between python assignment and deep copy

1. Copy and copy

Assignment is a reference to an object, and deep copy is to create a new object

Assigning a to b, the addresses of a, and b are exactly the same, indicating that a and b are still the same object, just aliased

And the addresses of copy_a, deepcopy_a and a are inconsistent, indicating that copy_a, deepcopy_a reopened the address space to store new objects.

Therefore, the operation on b is equivalent to the operation on a, and whether it is a deep copy or a shallow copy, the operation on the new object will not affect the original object (the object does not have sub-objects)


2. Deep copy and shallow copy

When the object has child objects, shallow copy will only copy the parent object, and for child objects, only the id will be copied;

The deep copy will recursively find the contents of the sub-object, and re-open space to store a copy, and then assign it to the new object

In the shallow copy, when the value 4 is added to the first layer of the new object copy_a, the original object a is not affected; when the value 44 is added to the child object, the value 44 is also added to a.

When deep copying, adding a value of 5 to the first layer of the new object deepcopy_a and adding a value of 55 to the child object does not affect the original object a.

Therefore, shallow copy only copies the ID of the parent object and child object, and the child object copy is actually a reference; while the deep copy will completely copy the parent object and child object, and the new object is completely independent of the original object.

Guess you like

Origin blog.csdn.net/kk_gods/article/details/110196156