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

Pierre GM pgmdevlist at gmail.com
Mon Feb 5 12:25:00 EST 2007


On Monday 05 February 2007 11:32:22 Jeremy Conlin wrote:
> Thanks for clarifying that.  I didn't understand what the
> __array_finalize__ did.

That means I should clarify some points on the wiki, then. 
A good exercise is to put some temporary comments in your code in __new__ and 
__array_finalize__, to show when these methods are called and how (that's how 
I learned)

Thinking about it, the example you gave can't work. Your __new__ method 
returns H, viz, a pure ndarray. There won't be any call to __array_finalize__ 
in that case, which is not what you want. Force the call by accessing a view 
of your array:

class myhistog(N.ndarray):
    def __new__(self, iniarray, inibin):
        (H,edges) = N.histogramdd(iniarray,inibin)
        self._defedges = edges
        return H.view(self)

Now, you do return a 'myhistog' class, not a pure 'ndarray', and 
__array_finalize__ is called.

    def __array_finalize__(self, obj):
        print "__array_finalize__ got %s as %s" % (obj, type(obj))
        if not hasattr(self, 'edges'):
            self.edges = self._defedges
	myhistog._defedges = None

Note the last line: you reset the class default to None (if this is what you 
want). Otherwise, new 'myhistog' objects wil inherit the previous edges.




More information about the NumPy-Discussion mailing list