[Numpy-discussion] Please help with subclassing numpy.ndarray

Stefan van der Walt stefan at sun.ac.za
Tue Feb 6 07:56:01 EST 2007


On Tue, Feb 06, 2007 at 01:06:37PM +0100, Sturla Molden wrote:
> 
> > def __new__(cls,...)
> >      ...
> >     (H, edges) = numpy.histogramdd(..)
> >     cls.__defaultedges = edges
> >
> > def __array_finalize__(self, obj):
> >     if  not hasattr(self, 'edges'):
> >         self.edges = self.__defaultedges
> 
> IMHO, the preferred way to set an instance attribute is to use __init__
> method, which is the 'Pythonic' way to do it.

I don't pretend to know all the inner workings of subclassing, but I
don't think that would work, given the following output:

In [1]: import numpy as N

In [2]: import numpy as N

In [3]: 

In [3]: class MyArray(N.ndarray):
   ...:     def __new__(cls,data):
   ...:         return N.asarray(data).view(cls)
   ...:     
   ...:     def __init__(self,obj):
   ...:         print "This is where __init__ is called"
   ...:         
   ...:     def __array_finalize__(self,obj):
   ...:         print "This is where __array_finalize__ is called"
   ...: 

In [4]: x = MyArray(3)
This is where __array_finalize__ is called
This is where __init__ is called

In [5]: y = N.array([1,2,3])

In [6]: x+y
This is where __array_finalize__ is called
Out[6]: MyArray([4, 5, 6])


Regards
Stéfan



More information about the NumPy-Discussion mailing list