a = [1,2,3]

b = a

b = a.copy()

# 1. 对象的嵌套引用

a = { "list": [1,2,3] }

# 1. 浅拷贝

## 1.1 浅拷贝的方法

• .copy()

a = {"list": [1,2,3] }
b = a.copy()
• copy模块

import copy
a = {"list": [1,2,3] }
b = copy.copy(a)
• 列表切片[:]

a = [1,2,3,[1,2,3]]
b = a[1:]
• for循环

a = [1,2,3,[1,2,3]]
b = []
for i in a:
b.append(i)

## 1.2 浅拷贝的影响

a = {"list":[1,2,3]}
b = a.copy()
a["list"].append(4)

print(a)
# {'list': [1, 2, 3, 4]}

print(b)
# {'list': [1, 2, 3, 4]}

# 2. 深拷贝

import copy
a = {"list":[1,2,3]}
b = copy.deepcopy(a)
a["list"].append(4)

print(a)
# {'list': [1, 2, 3, 4]}

print(b)
# {'list': [1, 2, 3,]}

# 3. 手动实现一个深拷贝

def deepcopy(instance):
if isinstance(instance, dict):
return {k:deepcopy(v) for k,v in instance.items() }

elif isinstance(instance, list):
return [deepcopy(x) for x in instance]

else:
return instance

a = {"list": [1,2,3]}
b = deepcopy(a)

print(a)
# {'list': [1, 2, 3]}

print(b)
# {'list': [1, 2, 3]}

a["list"].append(4)
print(a)
# {'list': [1, 2, 3, 4]}

print(b)
# {'list': [1, 2, 3]}