-
Foreword :…
-
table of Contents
-
Direct assignment: In fact, it is the reference (alias) of the object.
-
Shallow copy (copy): Copy the parent object without copying the child objects inside the object.
-
Deep copy (deepcopy): The deepcopy method of the copy module completely copies the parent object and its children.
1 Shallow copy
>>>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 needs to introduce 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]})
- Parsing
- b = a: Assignment reference, both a and b point to the same object.
- b = a.copy(): shallow copy, a and b are independent objects, but their child objects still point to a unified object (reference).
b = copy.deepcopy(a): deep copy, a and b completely copy the parent object and its children, and the two are completely independent.
2 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']] #原始对象
b = a #赋值,传对象的引用
c = copy.copy(a) #对象拷贝,浅拷贝
d = copy.deepcopy(a) #对象拷贝,深拷贝
a.append(5) #修改对象a
a[4].append('c') #修改对象a中的['a', 'b']数组对象
print( 'a = ', a )
print( 'b = ', b )
print( 'c = ', c )
print( 'd = ', d )
The execution output 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']])