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?