Python 中的一切都是对象,以下代码:
赋值
赋值只是简单地使新变量指向已经存在的对象:
numbers = [1, 2, 3, 4, 5]
new_numbers = numbers
numbers
与 new_numbers
指向相同的对象,修改 numbers
就是在修改 new_numbers
。
id(numbers) == id(b)
或者 numbers is new_numbers
都为 True
.
浅拷贝与深拷贝
浅拷贝和深拷贝之间的区别仅与复合对象(包含其他对象的对象,如列表或类实例)相关。
浅拷贝复制得到新的复合对象,但引用原始对象的元素。
深拷贝复制得到新的复合对象,并复制该组成原始对象的元素。
要复制对象,需要使用内建模块 copy
调用 copy.copy()
实现浅拷贝:
import copy
old_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
shallow_list = copy.copy(old_list)
print(old_list)
print(shallow_list)
print(old_list is shallow_list)
print(old_list[0] is shallow_list[0])
old_list[0][0] = "x"
print(old_list)
print(shallow_list)
输出:
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
False
True
[['x', 2, 3], [4, 5, 6], [7, 8, 9]]
[['x', 2, 3], [4, 5, 6], [7, 8, 9]]
调用 copy.deepcopy()
实现浅拷贝:
old_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
deep_list = copy.deepcopy(old_list)
print(old_list)
print(deep_list)
print(old_list is deep_list)
print(old_list[0] is deep_list[0])
old_list[0][0] = "x"
print(old_list)
print(deep_list)
输出:
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
False
False
[['x', 2, 3], [4, 5, 6], [7, 8, 9]]
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]