python中有一個copy模塊惶傻,他提供shallow copy與deep copy兩種方式,shallow copy與deep copy有一些區(qū)別壹瘟。
shallow copy與deep copy出來的數(shù)據(jù)鲫剿,一樣在內(nèi)存中都存在兩份,但是shallow copy出的內(nèi)容id一致稻轨,而deep copy出的數(shù)據(jù)連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]