-
Direct assignment: In fact, it is a reference (alias) of the object.
-
Shallow copy (copy): copies the parent object and does not copy the internal child objects of the object.
-
Deepcopy: The deepcopy method of the copy module completely copies the parent object and its child objects.
Dictionary shallow copy example
>>>a = {1: [1,2,3]}
>>> b = a.copy()
>>> a, b
({1: [1, 2, 3]}, {1: [1, 2, 3]})
>>> a[1].append(4)
>>> a, b
({1: [1, 2, 3, 4]}, {1: [1, 2, 3, 4]})
Deep copy requires the introduction of the copy module:
>>>import copy
>>> c = copy.deepcopy(a)
>>> a, c
({1: [1, 2, 3, 4]}, {1: [1, 2, 3, 4]})
>>> a[1].append(5)
>>> a, c
({1: [1, 2, 3, 4, 5]}, {1: [1, 2, 3, 4]})
Analysis
1.b = a: Assignment reference, both a and b point to the same object.
2.b = a.copy(): Shallow copy, a and b are an independent object, but their sub-objects still point to the same object (reference).
3.b = copy.deepcopy(a): Deep copy, a and b completely copy the parent object and its child objects, and they are completely independent.
More examples
The following examples are copy.copy (shallow copy) and (copy.deepcopy) using the copy module
#!/usr/bin/python
# -*-coding:utf-8 -*-
import copy
a = [1, 2, 3, 4, ['a', 'b']] #original object
b = a #Assignment, passing the reference of the object
c = copy.copy(a) #Object copy, shallow copy
d = copy.deepcopy(a) #Object copy, deep copy
a.append(5) #Modify object a
a[4].append('c') #Modify the ['a', 'b'] array object in object a
print( 'a = ', a )
print( 'b = ', b )
print( 'c = ', c )
print( 'd = ', d )
The output result of the execution of the above example is
('a = ', [1, 2, 3, 4, ['a', 'b', 'c'], 5])
('b = ', [1, 2, 3, 4, ['a', 'b', 'c'], 5])
('c = ', [1, 2, 3, 4, ['a', 'b', 'c']])
('d = ', [1, 2, 3, 4, ['a', 'b']])
Post comment 取消回复