简体   繁体   中英

Subclassing numpy ndarray breaks at __getitem__

A very very basic ndarray subclass (which doesn't do anything yet) is laid out below. However the print function (or better, __getitem__() ) doesn't work.

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 is shown correctly (and as expected the 6 values are random). However the print y (or print(y[0,0]) ) returns the following error:

 return np.ndarray.__getitem__(key) 

TypeError: descriptor __getitem__ requires a 'numpy.ndarray' object but received a 'int'

So how do I subclass correctly (and catch the set/getitem)

You must pass the self too, either

return np.ndarray.__getitem__(self, key)

or

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM