浅拷贝
a = [1,2,3]
b = a # a is b 这两个变量指向同一片内存地址
# 即如果a的值别修改了,b的值也会被修改
深拷贝
import copy
copy.deepcopy(var) # 会递归,将所有为地址的变量都拷贝一份。(即完全生成一份新的东西)
copy.copy(var) # 一般只拷贝一层(对于不可变类型不起作用)
import copy
a = [1,2,3]
b = copy.deepcopy(a)
c = copy.copy(a)
#这里 b、c都会产生新的地址,相当于a、b、c是三块内存地址
#因为列表内部不是地址,copy和deepcopy只是做了一层拷贝即可
import copy
a = [1,2,3]
b = [4,5,6]
c = [a,b]
d = copy.copy(c) #这里只做了一层拷贝。即开辟一块新的地址,存放a与b变量
e = copy.deepcopy(c) #这里不光开辟一块新的地址,因为a、b都是地址,所以同时也拷贝a、b生成新的地址存在e中
print(d is e, e is c, c is d) # False False False
print(d == e, e == c, c == d) # True True True
a.append(10)
print(d == e, e == c, c == d) # False False True
# 因为后面修改了a的值,c与e就不相等了,但是c与d还是相等
import copy
a = [1,2,3]
b = [4,5]
c = (a,b)
d = copy.copy(c)
e = copy.deepcopy(c)
print(d is c, e is c) # True False
b.append(6)
print(d is c, e is c) # True False
print(d is c, d[1] is c[1]) # True True
print(e[1] is c[1], e[1] == c[1], e[0] == c[0]) False False True
# 分析,对于元组这样不可变类型,copy不起作用,而deepcopy还是依然强悍,会逐层拷贝。