import copy
'''
拷贝种类:
1、=赋值式浅拷贝(不需要进行类型区分,皆为浅拷贝)
2、浅拷贝(copy):引用同一内存地址,更新内容会相互影响(需要注意外层为可变类型情况)
3、深拷贝(deepcopy):开辟不同内存地址,更新内容不会相互影响(区分可变与不可变类型)
'''
def main():
print(f'{"-" * 50}=赋值式浅拷贝{"-" * 50}')
a = [1, 2, [3, 4]]
b = a
a.append(3)
b.append(4)
a[2].append(5)
b[2].append(6)
print(a)
print(b)
print(id(a))
print(id(b))
print(id(a[2]))
print(id(b[2]))
print(f'{"-" * 50}浅拷贝(copy){"-" * 50}')
a = [1, 2, [3, 4]]
b = copy.copy(a)
a.append(3)
b.append(4)
a[2].append(5)
b[2].append(6)
print(a)
print(b)
print(id(a))
print(id(b))
print(id(a[2]))
print(id(b[2]))
print(f'{"-" * 50}深拷贝(deepcopy){"-" * 50}')
a = [1, 2, [3, 4]]
b = copy.deepcopy(a)
a.append(3)
b.append(4)
a[2].append(5)
b[2].append(6)
print(a)
print(b)
print(id(a))
print(id(b))
print(id(a[2]))
print(id(b[2]))
if __name__ == '__main__':
main()
|