2

A very very basic ndarraysubclass (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)

1 Answer 1

4

You must pass the self too, either

return np.ndarray.__getitem__(self, key)

or

return super(imarray, self).__getitem__(key)
Sign up to request clarification or add additional context in comments.

1 Comment

@not doing anything, I removed the "doing" for the sake of providing the minimal example.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.