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

Pierre GM pgmdevlist at gmail.com
Fri Nov 23 11:05:08 EST 2007

> 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 ?

Mmh, I would at least try to explicitly call the N.memmap.__new__

> 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

OK, I'll edit the example

> 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."""

Yeah, that's not very clear.
Well, look at the code of the example.
In line 11, we call a view of the array, with our class as argument. That 
calls __array_finalize__, with "subarr" as the obj argument.  
__array_finalize__ sets a default "info" attribute: an empty dictionary, as 
the argumnet doesn't have an info attribute yet. 
In lines 14-18, we set the "info" argument of our object to the value we want.

> 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.

OK, same as for 1.

> 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 ?

As a rule of thumb, __new__ is called each time you have a construction like 
MyClass(whatverargumentisneeded). When you rely on views (such as w/ 
the .view method, or ravel, or transpose...), you call __array_finalize__ . 
You don't really have to study the numpy code (even if it helps)

> 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) ?

Try. The ndarray doesn't have a **keywords option: you can't pass extra 
parameters to ndarray.__new__. In other terms, if you need to pass some 
specific parameter to your class (in our example, info), you'll choke 

More information about the NumPy-Discussion mailing list