[Numpy-discussion] my derived ndarray class object loses its attribute after a transpose()

Sebastian Haase haase at msg.ucsf.edu
Fri Nov 23 10:43:12 EST 2007


On Nov 23, 2007 3:37 PM, Pierre GM <pgmdevlist at gmail.com> wrote:
> On Friday 23 November 2007 03:25:37 Sebastian Haase wrote:
> > Hi,
> > this question might habe been answered before:
> > I have my own ndarray-derived class. I did this, so that I can add
> > another "custom attribute" -- let's say
> > arr.filename
>
> Sebastian,
> Could you post the __new__ and __array_finalize__ for your class ? Are you
> sure you update the attribute in __array_finalize__ ?
> And this page may come handy:
> http://www.scipy.org/Subclasses

Aah - I guess I did not do my homework ;-)
Here is my code:
        class ndarray_inMrcFile(N.memmap):
            pass

        data = self.data
        data.__class__ = ndarray_inMrcFile

Two points:
1.) Please don't get distracted by the way how I change the class type
"after the fact". I get the data as a memmaped slice from a file. Then
I do some (potentially not entirely clean) acrobatic to have this
slice change it's class-type so that I can attach the original memmap
(+ other attributes, such as filename) onto the ndarray

2.) I guess the   """class ndarray_inMrcFile(N.memmap):
pass""" construct is to simplistic ....
   Could someone suggest a *minimal* definition, so that my attributes
would be preserved ?


A few comments about the wiki page:
1)  The example does not show the printed info, such as "__new__
received %s", in the example session

2) I don't understand, why in the example the "info" attribute is set
in "__new__()", even though the text above says:
"""However, we need to keep in mind that any attribute that we define
in the __new__ method will be shared among all the instances. If we
want instance-specific attributes, we still need some specific
initialization. We cannot use the __init__ method, as it won't be
called. That's where __array_finalize__ comes to play."""

3) the text about "The __array_finalize__ method"  should at least
once say that it is defined as "def __array_finalize__(self,obj)"  --
otherwise I could only guess where the "obj" comes from.

4) related to the text after: "In other terms, __array_finalize__ is called"
How do I know if a function or method actually  invokes __new__  ;-)
?  Would I have to study the numpy source ?

5) For the "__array_finalize__ method" there a text that says:
"""Subclasses inherit a default implementation of this method that
does nothing""" --- but how about "__new__()" :  what happens if you
don't define that (either) ?

(Hope these comments are helpful)

Thanks for the help,
Sebastian



More information about the NumPy-Discussion mailing list