[Numpy-discussion] Please help with subclassing numpy.ndarray
Travis Oliphant
oliphant at ee.byu.edu
Wed Feb 7 16:36:39 EST 2007
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.
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.
-Travis
More information about the NumPy-Discussion
mailing list