我试图在ndarray上使用deepcopy,这条线看起来像这样:
foo = myArray.__deepcopy__()
我得到了:
TypeError: function takes exactly 1 argument (0 given)
我需要一份深层复印件,而我无法导入复印件。
答案 0 :(得分:2)
特殊__deepcopy__
方法需要memo
arg。你可以为此传递一个空字典:
foo = myArray.__deepcopy__({})
答案 1 :(得分:2)
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
可能会有所不同。备忘录当然看起来不同。
答案 2 :(得分:1)
copy
module包含__deepcopy__
的文档,很明显该论点应该是什么:
为了让类定义自己的副本实现,它可以定义特殊方法
__copy__()
和__deepcopy__()
。前者被称为实现浅拷贝操作;没有传递其他参数。调用后者来实现深拷贝操作; 传递一个参数,即备忘录词典。
但是,如果您没有实施自定义的深层复制课程,通常不需要为此烦恼,只需使用copy.deepcopy
:
from copy import deepcopy
import numpy as np
arr = np.random.random((100, 100))
deepcopy(arr)
如果没有你的干预,它会处理memo
- dict。注意:大多数__*__
都采用这种方式设计,您通常不会直接调用它们。因此,与使用x in y
代替y.__contains__(x)
一样,您通常使用copy.deepcopy(x)
代替x.__deepcopy__(dict())
。