copy模块

概念

Assignment statements in Python do not copy objects, they create bindings between a target and an object. For collections that are mutable or contain mutable items, a copy is sometimes needed so one can change one copy without changing the other. This module provides generic shallow and deep copy operations.

在Python中,赋值语句不拷贝对象,而是在对象和变量指尖建立联系。对于可变集合,拷贝有时候是需要的,以便于可以在改变一个拷贝的同时不改变另一个拷贝。这个模块提供了通用的浅拷贝和深拷贝操作

用法

import copy 

a = [1, 2]   # a可以是任意对象
b = copy.copy(a) # 浅拷贝
b = copy.deepcopy(a) # 深拷贝

比较

浅拷贝 vs. 直接赋值

import copy
# assignment directly
a = [1, 2]
a[0] = 3
print(a)
# shallow copy
a = [1, 2]
b = copy.copy(a)
b[0] = 3
print(a)

# result:
# [3, 2]
# [1, 2]

解释

说明浅拷贝使得a和b指向不同的对象

深拷贝 vs. 浅拷贝

import copy 
# shallow copy
a = [1, 2, [3, 4]]
b = copy.copy(a)
b[2][0] = 5
print(a)
# deep copy
a = [1, 2, [3, 4]]
b = copy.deepcopy(a)
b[2][0] = 5
print(a)

# result:
# [1, 2, [5, 4]]
# [1, 2, [3, 4]]

解释

说明对于像a这样的复合对象,浅拷贝只拷贝了父对象,而深拷贝拷贝了所有嵌套的对象

你可能感兴趣的:(copy模块)