[SciPy-User] subclassing ndarray : i want slice to return ndarray, not subclass

Dag Sverre Seljebotn d.s.seljebotn at astro.uio.no
Mon May 21 07:42:07 EDT 2012


On 05/21/2012 11:56 AM, pierre puiseux UPPA wrote:
> Hello,
> all my question is in the title. More precisely, like in scipy doc i try
> this :
> ======================================
> importsys
> import numpy as np
>
> class ArrayChild(np.ndarray):

Subclassing ndarray is a very tricky business -- I did it once and 
regretted having done it for years, because there's so much you can't do 
etc.. You're almost certainly better off with embedding an array as an 
attribute, and then forward properties etc. to it.

But your answer: You want to override __getitem__, __getslice__ is 
deprecated in Python.

Dag

>
> def __new__(cls, array, info=None):
> obj = np.asarray(array).view(cls)
> obj.info = info
> return obj
>
> def __array_finalize__(self, obj):
> print>>sys.stderr, "__array_finalize__"
> if obj is None: return
> self.info = getattr(obj, 'info', None)
>
> if __name__=='__main__':
> a = np.arange(6)
> a.shape=2,3
> a_child = ArrayChild(a)
> for x in a_child :
> print>>sys.stderr, x, type(x)
>
> =====================================
> and i have the answer :
> =====================================
> __array_finalize__
> __array_finalize__
> [0 1 2] <class '__main__.ArrayChild'>
> __array_finalize__
> [3 4 5] <class '__main__.ArrayChild'>
>
> =====================================
> but i want
> =====================================
> __array_finalize__
> __array_finalize__
> [0 1 2] <class '__main__.np.ndarray'>
> __array_finalize__
> [3 4 5] <class '__main__.np.ndarray'>
>
> =====================================
> I've tried to redefine : __getslice__ like this, but it does not work.
> =====================================
> def __getslice__(self, *args, **kwargs):
> return np.ndarray.__getslice__(self, *args, **kwargs)




More information about the SciPy-User mailing list