子类numpy ndarray在__getitem__中断

时间:2015-03-30 13:16:39

标签: python arrays numpy

下面列出了一个非常基本的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)

1 个答案:

答案 0 :(得分:3)

您也必须传递self

return np.ndarray.__getitem__(self, key)

return super(imarray, self).__getitem__(key)