浅析Python中深拷贝和浅拷贝
按照以下不同情况,在IDE中逐个解除注释,就明白了
import copy"""第一种情况,不可变类型变量,都是引用"""# a = 1# a = (11, 222, 333)# a = 'string'# a = True# b = a## print(id(a))# print(id(b))## c =copy.copy(a)# d = copy.deepcopy(a)# print(id(c))# print(id(d))"""第二种情况,可变类型变量,浅拷贝和深拷贝都开辟了空间备注:[(1,2),3]外层可变,内层不可变,同此类型。"""# a = [2, 3, 4]# # a = {2,5,6}# # a = {"name": "jim"}# b = a# c =copy.copy(a)# d = copy.deepcopy(a)## print(id(a))# print(id(b))# print(id(c))# print(id(d))## # ................# a.append(5)# # ----------------## print(a)# print(b)# print(c)# print(d)"""第三种情况,内外层都是不可变类型的,深浅拷贝都是引用"""# a = ((1,2),)# b = a# c =copy.copy(a)# d = copy.deepcopy(a)## print(id(a))# print(id(b))# print(id(c))# print(id(d))### print(a)# print(b)# print(c)# print(d)"""第四种情况,外层不可变,内层可变,因为浅拷贝对不可变类型只是指向了,也即引用了内存地址,深拷贝重新开辟了内存地址。"""# e = 1# f = 2# list1 = [e, f]# a = (list1,) # a= ([1,2],)# b = a## print(id(a))# print(id(b))## c =copy.copy(a)# d = copy.deepcopy(a)# print(id(c))# print(id(d))## list1.append(8)## print(id(a))# print(id(b))# print(id(c))# print(id(d))# print(a)# print(b)# print(c)# print(d)"""第五种情况,外层可变,内层可变----真正体现浅拷贝和深拷贝的差距,a[:]是一种浅拷贝。深浅拷贝都重新开辟了内存空间,浅拷贝的内层元素只是引用了内存地址,深拷贝的内层元素也重新开辟了内存空间。"""e = 1f = 2list1= [e,f]g = 3h = 4list2 = [g,h]a = [list1,list2]b = ac =copy.copy(a)d = copy.deepcopy(a)print(id(a))print(id(b))print(id(c))print(id(d))print(a)print(b)print(c)print(d)print("*" * 20)# 改变e或者f的元素list1.append('list1')print(id(a))print(id(b))print(id(c))print(id(d))print(a)print(b)print(c)print(d)print("*" * 20)a.append('a')print(id(a))print(id(b))print(id(c))print(id(d))print(a)print(b)print(c)print(d)
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。