Subclassing numpy.ndarray

I want to implement a subclass numpy.ndarray

that overrides the constructor 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

.

Installing a class ret

using

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

      

will not 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 great for small n

, but I'd rather avoid additional assignment on the Python side when n

large.

Is there any other approach that would avoid this additional assignment and still create an object of the class mymat

?

+3


source to share


1 answer


Try the following:



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

      

+4


source







All Articles