copy中的相关代码为:
def deepcopy(x, memo=None, _nil=[]):
"""Deep copy operation on arbitrary Python objects.
See the module's __doc__ string for more info.
"""
if memo is None:
memo = {}
....
copier = getattr(x, "__deepcopy__", None)
if copier:
y = copier(memo)
...
# If is its own copy, don't memoize.
if y is not x:
memo[d] = y
_keep_alive(x, memo) # Make sure x lives at least as long as d
return y
所以memo 是一个memoize 字典,至少在“正确”使用时是这样
所以如果我将字典传递为memo,它会改变:
In [160]: dd={}
In [161]: A2=copy.deepcopy(A,memo=dd)
In [162]: dd
Out[162]:
{2814755008: array([[[0, 1, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 1],
[0, 0, 0, 1, 0, 1],
[1, 0, 0, 0, 1, 0]],
[[0, 0, 1, 0, 0, 0],
[0, 0, 1, 1, 0, 0],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0]]]), 2814808588: [array([[[0, 1, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 1],
[0, 0, 0, 1, 0, 1],
[1, 0, 0, 0, 1, 0]],
[[0, 0, 1, 0, 0, 0],
[0, 0, 1, 1, 0, 0],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0]]])]}
In [163]: id(A)
Out[163]: 2814755008
In [167]: id(dd[id(A)])
Out[167]: 2814568472
In [168]: id(A2)
Out[168]: 2814568472
memo 保留副本的记录。我不知道第二项是什么。
如果我要求另一个具有相同备忘录的深层副本,它会给出已记忆的数组而不是新副本。
In [173]: A3=copy.deepcopy(A,memo=dd)
In [174]: id(A2)
Out[174]: 2814568472
In [175]: id(A3)
Out[175]: 2814568472
如果数组是对象 dtype,deepcopy 可能会有所不同。备忘录看起来确实不一样。