python中深拷贝与浅拷贝

时间:2022-05-16 00:21:02

# 1.浅拷贝(复制东西)
a = [11,22,33]

# 实际上是浅拷贝
# 没有把这个变量的值赋进去,而是把另一个变量的地址拿过去了,就叫浅拷贝。
b = a

# print(id(a))
# print(id(b))

# 什么是深拷贝
import copy
c = copy.deepcopy(a) # 深拷贝

print(id(a))
print(id(c))

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

# 深拷贝和浅拷贝
aa = [11,22,33]
bb = [44,55,66]

c = [a,b]

# deepcopy深度识别

'''
>>> a = [11,22,33]
>>> b = [44,55,66]
>>> c = [a,b]
>>> c
[[11, 22, 33], [44, 55, 66]]
>>> d = c
>>> d
[[11, 22, 33], [44, 55, 66]]
>>> id(d)
2711060056904
>>> id(c)
2711060056904
>>> import copy
>>> e = copy.deepcopy(c)
>>> id(e)
2711060078984
>>> id(e[0])
2711060056968
>>> id(a)
2711060055432
>>> a.append(44)
>>> e
[[11, 22, 33], [44, 55, 66]]
>>> c
[[11, 22, 33, 44], [44, 55, 66]]
>>>
'''

# 对于列表
# copy.copy copy只能识别第一层
'''
>>> a = [1,2,3]
>>> b = [4,5,6]
>>> c = [a,b]
>>> e = copy.copy(c)
>>> e
[[1, 2, 3], [4, 5, 6]]
>>> a.append(4)
>>> e
[[1, 2, 3, 4], [4, 5, 6]]
>>> c
[[1, 2, 3, 4], [4, 5, 6]]
>>>
'''

# 对于元组

# copy.copy 如果是不可变类型,就不深拷贝,如果是可变类型,就只能拷贝一层
# >>> a = [1,2,3]
# >>> b = [4,5,6]
# >>> c = (a,b)
# >>> e = copy.copy(c)
# >>> id(c)
# 2711060057352
# >>> id(e)
# 2711060057352
# >>>

# 使用copy模块的copy会根据当前的拷贝的数据类型是可变类型还是不可变类型存在的不同的处理方式