[Numpy-discussion] subclassing ndaray

Stefan van der Walt stefan at sun.ac.za
Sat Feb 25 00:41:01 CST 2006


On Fri, Feb 24, 2006 at 06:40:16PM -0700, Travis Oliphant wrote:
> Stefan van der Walt wrote:
> 
> >I see the same strange result.  Here is a minimal code example to
> >demonstrate:
> >
> >import numpy as N
> >
> >class Bar(N.ndarray):
> >   v = 0.
> >   
> >   def __new__(cls, *args, **kwargs):
> >	print "running new"
> >	return super(Bar, cls).__new__(cls, *args)
> >
> >   def __init__(self, *args, **kwargs):
> >	print "running init"
> >	self[:] = 0
> >	self.v = 3
> > 
> >
> It's only strange if you have assumptions your not revealing.  Here's 
> the deal.
> 
> Neither the __init__ method nor the __new__ method are called for c = b+1.
> 
> So, your wondering how the Bar object got created then right?  Well, it 
> got created as a subclass of ndarray in PyArray_NewFromDescr. 
> 
> The __init__ and __new__ methods are not called because they may have 
> arbitrary signatures.  Instead,  the __array_finalize__ method is always 
> called.  So, you should use that instead of __init__.
> 
> The __array_finalize__ method always receives the argument of the 
> "parent" object.
> 
> Thus in your case.
> 
>       def __array_finalize__(self, parent):
>             self.v = 3
> 
> would do what you want.

That doesn't seem to work.  __array_finalize__ isn't called when the
object is initially constructed:

In [14]: b = Bar(2)
running new

In [15]: b.v
Out[15]: 0.0

In [16]: b=b+1

In [17]: b.v
Out[17]: 3

Should a person then call __array_finalize__ from __init__?

Stéfan




More information about the Numpy-discussion mailing list