User guide

NumPy User Guide, Release 1.9.0
2.8.4 Creating new from template
New instances of an ndarray subclass can also come about by a very similar mechanism to View casting, when numpy
finds it needs to create a new instance from a template instance. The most obvious place this has to happen is when
you are taking slices of subclassed arrays. For example:
>>> v = c_arr[1:]
>>> type(v) # the view is of type ’C’
<class ’C’>
>>> v is c_arr # but it’s a new instance
False
The slice is a view onto the original c_arr data. So, when we take a view from the ndarray, we return a new ndarray,
of the same class, that points to the data in the original.
There are other points in the use of ndarrays where we need such views, such as copying arrays (c_arr.copy()),
creating ufunc output arrays (see also __array_wrap__ for ufuncs), and reducing methods (like c_arr.mean().
2.8.5 Relationship of view casting and new-from-template
These paths both use the same machinery. We make the distinction here, because they result in different input to your
methods. Specifically, View casting means you have created a new instance of your array type from any potential
subclass of ndarray. Creating new from template means you have created a new instance of your class from a pre-
existing instance, allowing you - for example - to copy across attributes that are particular to your subclass.
2.8.6 Implications for subclassing
If we subclass ndarray, we need to deal not only with explicit construction of our array type, but also View casting or
Creating new from template. Numpy has the machinery to do this, and this machinery that makes subclassing slightly
non-standard.
There are two aspects to the machinery that ndarray uses to support views and new-from-template in subclasses.
The first is the use of the ndarray.__new__ method for the main work of object initialization, rather then the
more usual __init__ method. The second is the use of the __array_finalize__ method to allow subclasses
to clean up after the creation of views and new instances from templates.
A brief Python primer on __new__ and __init__
__new__ is a standard Python method, and, if present, is called before __init__ when we create a class instance.
See the python __new__ documentation for more detail.
For example, consider the following Python code:
class C(object):
def __new__(cls,
*
args):
print ’Cls in __new__:’, cls
print ’Args in __new__:’, args
return object.__new__(cls,
*
args)
def __init__(self,
*
args):
print ’type(self) in __init__:’, type(self)
print ’Args in __init__:’, args
meaning that we get:
36 Chapter 2. Numpy basics