-
Direct assignment: in fact, object reference (alias).
-
Shallow copy (copy): sub-objects inside a copy of the parent object, the object will not be copied.
- Deep copy (DeepCopy): DeepCopy method copy module, complete copy of the parent object and child objects.
Direct assignment : a and b point to the same object
Shallow copy: b = a.copy (): shallow copy, a and b are a separate object, sub-object, or they point to a unified object (reference).
Such as:
import copy a = [1, {1,2,3}] b = copy.copy(a) a.append(2) print(a, b) #([1, set([1, 2, 3]), 2], [1, set([1, 2, 3])]) a[1].add(4) print(a, b) # ([1, set([1, 2, 3, 4]), 2], [1, set([1, 2, 3, 4])])
In the code shown above, after a.append (2), because a, b are independent objects, so a.append (2) does not affect the value of b. So the results print (a, b) are:
([1, set([1, 2, 3]), 2], [1, set([1, 2, 3])])。
However, a [1] and b [1] for the same object, a [1] .add (4) also affect b. So the results print (a, b) are:
([1, set([1, 2, 3, 4]), 2], [1, set([1, 2, 3, 4])])。
Deep copy: A complete copy of b and parent object and its children, the two are completely separate.
The sample above into shallow copy:
import copy
a = [1, {1,2,3}]
b = copy.deepcopy(a)
a.append(2)
print(a, b)
a[1].add(4)
print(a, b)
Results two print (a, b) are:
([1, set([1, 2, 3]), 2], [1, set([1, 2, 3])])
([1, set([1, 2, 3, 4]), 2], [1, set([1, 2, 3])])
可以发现对a,b的修改,完全不会影响b的值。