[Numpy-discussion] Please help with subclassing numpy.ndarray
Wed Feb 7 17:32:16 CST 2007
On Wed, 2007-02-07 at 14:36 -0700, Travis Oliphant wrote:
> 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
> >So in order to get an instance attribute, one has to temporarily define it
> >as a class attribute?
> No, you don't *have* to do it this way for all instance attributes.
> In this example, the user was trying to keep the edges computed during
> the __new__ method as an attribute. What are the possibilities?
> 1) Use the __new__ method to create the object in full and then store
> the edges in some kind of global (or class global) variable.
> This solution because it uses global variables has all of the thread
> problems global variables bring.
> 2) Create a "dummy" arrayobject in the __new__ method and fill it in
> (i.e. using setstate or resize) during the __init__ method where the
> instance attribute is actually set.
I'm probably missing something obvious here, but why can't you just
attach the attribute to the actual object in the __new__ method before
returning it. For example:
def __new__(self, ...):
# Some stuff here
H, edges = numpy.histogramdd(...)
result = H.view(MyClass)
result.edges = edges
def __array_finalize__(self, obj):
self.edges = getattr(obj, 'edges', )
If you could show me the error of my ways, it would help me in *my*
attempt to subclass ndarray.
> The __array_finalize__ method is intended for "passing-on" attributes to
> sub-classes from parent classes during operations where __new__ and
> __init__ are not called (but a new instance is still created). It was
> not intended to be used in all circumstances.
More information about the Numpy-discussion