Python 子类化uu getitem处的numpy ndarray中断__
下面列出了一个非常基本的NdaraySubclass,它不做任何事情。但是,打印功能或更好的功能,\uuuu getitem\uuuuu不起作用Python 子类化uu getitem处的numpy ndarray中断__,python,arrays,numpy,Python,Arrays,Numpy,下面列出了一个非常基本的NdaraySubclass,它不做任何事情。但是,打印功能或更好的功能,\uuuu getitem\uuuuu不起作用 class imarray(np.ndarray): def __new__(subtype, shape, dtype=float, buffer=None, offset=0, strides=None, order=None): # It also triggers a call to InfoArr
class imarray(np.ndarray):
def __new__(subtype, shape, dtype=float, buffer=None, offset=0,
strides=None, order=None):
# It also triggers a call to InfoArray.__array_finalize__
obj = np.ndarray.__new__(subtype, shape, dtype, buffer, offset, strides,
order)
return obj
def __getitem__(self, key):
return np.ndarray.__getitem__(key)
y = imarray((2,3))
x = np.ndarray((2,3))
print(x)
print(y)
x显示正确,如预期,6个值是随机的。但是,printy或printy[0,0]返回以下错误:
TypeError:描述符uu getitem_uuuu需要一个'numpy.ndarray'对象,但收到一个'int'
那么,如何正确地子类化并捕获set/getitem呢?您也必须传递self
return np.ndarray.__getitem__(self, key)
或
@没有做任何事情,为了提供最简单的示例,我删除了doing。
return np.ndarray.__getitem__(self, key)
return super(imarray, self).__getitem__(key)