python复制、浅拷贝、深拷贝

时间:2022-05-06 02:37:35
# 1.直接赋值,传递对象的引用而已,原始列表改变,被赋值的变量也会做相同的改变
A=[1,2,3,4,5,['aa','bb','cc']]
a = A
A.append('ee')
print(A) #[1, 2, 3, 4, 5, ['aa', 'bb', 'cc'], 'ee']
print(a) #[1, 2, 3, 4, 5, ['aa', 'bb', 'cc'], 'ee']

#2.copy--浅拷贝,没拷贝子对象,所以原始数据改变,子对象会改变
import copy
c = copy.copy(A)
print(c) #[1, 2, 3, 4, 5, ['aa', 'bb', 'cc'], 'ee']
print(A) #[1, 2, 3, 4, 5, ['aa', 'bb', 'cc'], 'ee']

A[5].append('ff')
print(A) #[1, 2, 3, 4, 5, ['aa', 'bb', 'cc', 'ff'], 'ee']
print(c) #[1, 2, 3, 4, 5, ['aa', 'bb', 'cc', 'ff'], 'ee'] #里面的子对象['aa','bb','cc']也变了

#3.深拷贝,包含对象里面的子对象拷贝,所以原始对象的改变不会造成深拷贝里任何子元素的改变
d = copy.deepcopy(A)
print(A) #[1, 2, 3, 4, 5, ['aa', 'bb', 'cc', 'ff'], 'ee']
print(d) #[1, 2, 3, 4, 5, ['aa', 'bb', 'cc', 'ff'], 'ee']

A[5].append('GG')
A.append(6)
print(A) #[1, 2, 3, 4, 5, ['aa', 'bb', 'cc', 'ff', 'GG'], 'ee', 6]
print(d) #[1, 2, 3, 4, 5, ['aa', 'bb', 'cc', 'ff'], 'ee'] 始终没有发生变化