实例深拷贝和浅拷贝的区别

import copy
alist = [1,2,3,[“a”,“b”]]

(1)直接赋值,默认浅拷贝传递对象的引用而已,原始列表改变,被赋值的b也会做相同的改变

b = alist
print(b) #[1, 2, 3, [‘a’, ‘b’]]
alist.append(5)
print(alist,b) #[1, 2, 3, [‘a’, ‘b’], 5] [1, 2, 3, [‘a’, ‘b’], 5]
#b和list 引用的相同的list 所以会相互改变 [1, 2, 3, [‘a’, ‘b’], 5, 6] [1, 2, 3, [‘a’, ‘b’], 5, 6]
b.append(6)
print(alist,b)

(2)copy浅拷贝,没有拷贝子对象,所以原始数据改变,子对象会改变

c = copy.copy(alist)
print(alist,c)

alist.append(5) #非可变对象 不会改变c
print(alist,c)
alist[3].append(‘cccc’) #子对象的list为公用可变 所以c会跟着改变
print(alist,c)

(3)深拷贝,包含对象里面的子对象的拷贝,所以原始对象的改变不会造成深拷贝里任何子元素的改变

#alist 和 d 完全独立于所有对象
d = copy.deepcopy(alist)
print(alist,d) #[1, 2, 3, [‘a’, ‘b’]] [1, 2, 3, [‘a’, ‘b’]]
alist.append(5)
print(alist,d) #[1, 2, 3, [‘a’, ‘b’], 5] [1, 2, 3, [‘a’, ‘b’]]
alist[3].append(‘cccc’)
print(alist,d) #[1, 2, 3, [‘a’, ‘b’, ‘cccc’], 5] [1, 2, 3, [‘a’, ‘b’]]

你可能感兴趣的:(python)