3

I want to implement a subclass of numpy.ndarray that overrides the constructor with something like this:

class mymat(numpy.ndarray):
    def __new__(cls, n, ...):
        ret = np.eye(n)

        # make some modifications to ret

        return ret

Unfortunately, the type of the object returned by this constructor is not cls, but rather numpy.ndarray.

Setting the class of ret with

ret.__class__ = cls # bombs: TypeError: __class__ assignment: only for heap types

won't work.

One possible solution would be something like

class mymat(numpy.ndarray):
    def __new__(cls, n, ...):
        ret = super(mymat, cls).__new__(cls, (n, n))
        ret[:] = np.eye(n)

        # make some modifications to ret

        return ret

This is fine for small n, but I'd prefer to avoid the extra Python-side assignment when n is large.

Is there some other approach that would avoid this extra assignment, and still produce an object of class mymat?

2

1 Answer 1

4

Try this:

class mymat(np.ndarray):
    def __new__(cls, n):
        ret = np.eye(n)
        return ret.view(cls)
Sign up to request clarification or add additional context in comments.

Comments

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.