python中有一个copy模块,他提供shallow copy与deep copy两种方式,shallow copy与deep copy有一些区别。
shallow copy与deep copy出来的数据,一样在内存中都存在两份,但是shallow copy出的内容id一致,而deep copy出的数据连id都修改了,完全是重新申请一遍变量。
import copy
class INT(object):
def __init__(self, value):
self.value = value
arg = INT(10)
a = [1,2,3,arg]
b = copy.copy(a) # shallow copy
c = copy.deepcopy(a) # deep copy
arg.value = 9
# a[3].value = 9
# b[3].value = 9
# c[3].value = 10
a.append(4)
# a = [1,2,3,arg,4]
# b = [1,2,3,arg]