User guide
NumPy User Guide, Release 1.9.0
Remember that subclass instances can come about in these three ways:
1. explicit constructor call (obj = MySubClass(params)). This will call the usual sequence of
MySubClass.__new__ then (if it exists) MySubClass.__init__.
2. View casting
3. Creating new from template
Our MySubClass.__new__ method only gets called in the case of the explicit constructor call, so we can’t rely
on MySubClass.__new__ or MySubClass.__init__ to deal with the view casting and new-from-template.
It turns out that MySubClass.__array_finalize__ does get called for all three methods of object creation, so
this is where our object creation housekeeping usually goes.
• For the explicit constructor call, our subclass will need to create a new ndarray instance of its
own class. In practice this means that we, the authors of the code, will need to make a call to
ndarray.__new__(MySubClass,...), or do view casting of an existing array (see below)
• For view casting and new-from-template, the equivalent of ndarray.__new__(MySubClass,... is
called, at the C level.
The arguments that __array_finalize__ recieves differ for the three methods of instance creation above.
The following code allows us to look at the call sequences and arguments:
import numpy as np
class C(np.ndarray):
def __new__(cls,
*
args,
**
kwargs):
print ’In __new__ with class %s’ % cls
return np.ndarray.__new__(cls,
*
args,
**
kwargs)
def __init__(self,
*
args,
**
kwargs):
# in practice you probably will not need or want an __init__
# method for your subclass
print ’In __init__ with class %s’ % self.__class__
def __array_finalize__(self, obj):
print ’In array_finalize:’
print ’ self type is %s’ % type(self)
print ’ obj type is %s’ % type(obj)
Now:
>>> # Explicit constructor
>>> c = C((10,))
In __new__ with class <class ’C’>
In array_finalize:
self type is <class ’C’>
obj type is <type ’NoneType’>
In __init__ with class <class ’C’>
>>> # View casting
>>> a = np.arange(10)
>>> cast_a = a.view(C)
In array_finalize:
self type is <class ’C’>
obj type is <type ’numpy.ndarray’>
>>> # Slicing (example of new-from-template)
>>> cv = c[:1]
In array_finalize:
38 Chapter 2. Numpy basics