[Numpy-discussion] how add new attribute to a numpy array object ?

Sebastian Haase haase at msg.ucsf.edu
Sun Jul 23 14:19:04 CDT 2006


Kevin Jacobs <jacobs at bioinformed.com> wrote:
> On 7/22/06, *Sebastian Haase* <haase at msg.ucsf.edu 
> <mailto:haase at msg.ucsf.edu>> wrote:
> 
>     Normally I could do
>     class B(N.ndarray):
>         pass
>     a=N.arange(10)
>     a.__class__ = B
> 
>     BUT I get this error:
>     #>>> a.__class__ = B
>     Traceback (most recent call last):
>        File "<input>", line 1, in ?
>     TypeError: __class__ assignment: only for heap types
> 
>     What is a "heap type" ? Why ?  How can I do what I want ?
> 
> 
> 
> Assigning to __class__ makes sense for objects that allocate a 
> dictionary for storage of attributes or have slots allocated to hold the 
> values.  The heap type error is due to a missing flag in the class 
> definition and could be corrected.  However, it may not be the best 
> thing to do.  Calling B(array) is certainly safer, although a bit more 
> expensive.
> 
> -Kevin
> 
Thanks for the replies.

Googling for this I was surprised myself that it IS legal (and done) to 
assign to obj.__class__.
Kevin,  I tried what you suggested first -- I think in C++ it would be 
called "using the copy-constructor".
But I get an error - something like:
"__new__() needs at least 3 arguments"
In other words: (maybe?) in Python there is not always a 
"copy-constructor"  (in fact there is no constructor overloading at all ...)

So if there is "just a missing flag" - it would be great if this could 
be put in.

It turns out that the "assigning to __class__"-scheme worked for the 
ndarray subclass "memmap"  (i.e. I was sub classing from memmap  and 
then I could assing origMemmapObj.__class__ = myClass)

Thanks,
Sebastian Haase




More information about the Numpy-discussion mailing list