下面列出了一个非常基本的ndarray
子类(它还没有做任何事情)。但是,打印功能(或更好,__getitem__()
)不起作用。
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个值是随机的)。但是,打印y(或print(y[0,0])
)会返回以下错误:
return np.ndarray.__getitem__(key)
TypeError:描述符
__getitem__
需要'numpy.ndarray'对象,但收到'int'
那么我如何正确子类化(并捕获set / getitem)
答案 0 :(得分:3)
您也必须传递self
return np.ndarray.__getitem__(self, key)
或
return super(imarray, self).__getitem__(key)