简体   繁体   中英

Subclassing numpy.ndarray

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 ?

Try this:

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

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