[Numpy-discussion] Simplest ndarray subclass __new__ possible?

Zachary Pincus zpincus at stanford.edu
Tue Feb 28 01:28:04 CST 2006


Thanks Travis,

I think I'm getting a hold on most of what's going on. The  
__array_priority__ bit remains a bit opaque (can anyone offer  
guidance?), and I still have some questions about why the __new__ of  
the matrix subclass ha so much complexity.

> So, if you over-write the __new__ constructor for your class and  
> want to call the ndarray.__new__ constructor you have to realize  
> that you need to think of what you are doing in terms of "wrapping"  
> some other created piece of memory or "initializing your memory".

This makes good sense.

> If you want your array to be-able to "convert" arbitrary objects to  
> arrays, instead, then your constructor could in-fact be as simple as
>
> class myarray(numpy.ndarray):
>          def __new__(cls, obj):
>                return numpy.array(obj).view(cls)

Ok, gotcha.

However, the matrix class's __new__ has a lot more complexity. Is  
*all* of the complexity there in the service of ensuring that  
matrices are only 2d? It seems like there's more going on there than  
just that...


> Then, if you want, you can define an __init__ method to handle  
> setting of attributes --- however, if you set some attributes, then  
> you need to think about what you want to happen when your new array  
> gets "sliced" or added to.  Because the internal code will create  
> your new array (without calling new) and then call
>
> __array_finalize__(self, parent)
>
> where parent could be None (if there is no parent --- i.e. this is  
> a new array).
>
> Any attributes you define should also be defined here so they get  
> passed on to all arrays that are created..

All of this also makes sense.

> I hope this helps some.
>
>
> -Travis
>




More information about the Numpy-discussion mailing list