数据浅/深拷贝
数据拷贝有两种,浅拷贝(shallow copy)以及深拷贝(deep copy)。从名字上可以看出来,浅拷贝,仅拷贝指向对象的指针;而深拷贝,是将整个对象拷贝到另外一块内存中。
浅拷贝
比如,我们有一个列表 [1, [1,2,3]]
,浅拷贝的话,列表中的第二个元素-列表 [1,2,3]
假如发生变化的话,它会同时在原始列表,以及浅拷贝后的列表做相同的改变,因为它们指向的是同一个内存地址。
A = [1, [1,2,3]]
B = A.copy()
A[1].append(4)
print(B)
#Out: [1, [1,2,3,4]]
print(A)
#Out: [1, [1,2,3,4]]
A[1] is B[1]
#Out: True
浅拷贝有两种实现方式,一个是用 copy()
方法,另外一个可以用 copy
模块里面的 copy
函数。
列表类型还有一种浅拷贝方法,就是通过切片来生成的新列表,也是浅拷贝的结果。
A = [1, [1,2,3]]
B = A[:]
B[1] is A[1]
#Out: True
深拷贝
深拷贝是完全的将被拷贝对象数据拷贝到新的内存中,新旧两个数据对象地址完全不同,它们是 100%独立的数据。
import copy
A = [1, [1,2,3]]
B = copy.deepcopy(A)
A is B
#Out: False
A[1].append(4)
print(A, B)
#Out: [1, [1, 2, 3, 4]] [1, [1, 2, 3]]
A[1] is B[1]
Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.
LinkedIn