按照以下不同情况,在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 = 1
f = 2
list1= [e,f]
g = 3
h = 4
list2 = [g,h]
a = [list1,list2]
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)
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)
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。