今日总结 – 57 – 浅拷贝(copy)和深拷贝(deepcopy)

请描述一下浅拷贝(copy)和深拷贝(deepcopy)的区别,请用代码举例说明如何使用copy和deepcopy

'''
copy: 只复制深层对象的引用
deepcopy: 复制深层对象的本身
'''
import copy
a = [1, 2, 3, 4, ['a', 'b']]

b = copy.copy(a) # 浅拷贝
c = copy.deepcopy(a) # 深拷贝
print(b)
print(c)

[1, 2, 3, 4, ['a', 'b']]

[1, 2, 3, 4, ['a', 'b']]

a.append(5)
print(a)
print(b)
print(c)

[1, 2, 3, 4, ['a', 'b'], 5]

[1, 2, 3, 4, ['a', 'b']]

[1, 2, 3, 4, ['a', 'b']]

a[4][0] = 'x'
print(a)
print(b)
print(c)

[1, 2, 3, 4, ['x', 'b'], 5]

[1, 2, 3, 4, ['x', 'b']]

[1, 2, 3, 4, ['a', 'b']]

正文完