[Numpy-discussion] simple subclassing of ndarray

Zachary Pincus zpincus at stanford.edu
Wed Feb 22 19:00:06 CST 2006


Hello folks,

I'm interested in creating a simple subclass of ndarray that just has  
a few additional methods. I've stared at defmatrix.py, but I'm not  
sure what is necessary to do.

Specifically, I'm not sure how to get new instances of my subclass  
created properly.

e.g.:
numpy.matrix([1,2,3])
Out: matrix([[1, 2, 3]])

class m(numpy.ndarray):
   pass
m([1,2,3])
Out: m([[[    13691,         0,         0],
         [   196608, 296292267, 296303312]]])

So clearly I need something else. Looking at the matrix class, it  
looks like I need a custom __new__ operator. However, looking at  
matrix's __new__ operator, I see a lot of complexity that I just  
don't understand. What's the minimum set of things I need in __new__  
to get a proper constructor?

Or perhaps there's a different and better way to construct instances  
of my subclass? Something akin to the 'array' function would be  
perfect. Now, how do I go about creating such a function (or getting  
'array' to do it)?

Can anyone give me any pointers here?

Thanks,

Zach Pincus

Program in Biomedical Informatics and Department of Biochemistry
Stanford University School of Medicine





More information about the Numpy-discussion mailing list