User guide

NumPy User Guide, Release 1.9.0
More information
You can find some more information on recarrays and structured arrays (including the difference between the two)
here.
2.8 Subclassing ndarray
2.8.1 Credits
This page is based with thanks on the wiki page on subclassing by Pierre Gerard-Marchant -
http://www.scipy.org/Subclasses.
2.8.2 Introduction
Subclassing ndarray is relatively simple, but it has some complications compared to other Python objects. On this
page we explain the machinery that allows you to subclass ndarray, and the implications for implementing a subclass.
ndarrays and object creation
Subclassing ndarray is complicated by the fact that new instances of ndarray classes can come about in three different
ways. These are:
1. Explicit constructor call - as in MySubClass(params). This is the usual route to Python instance creation.
2. View casting - casting an existing ndarray as a given subclass
3. New from template - creating a new instance from a template instance. Examples include returning slices from
a subclassed array, creating return types from ufuncs, and copying arrays. See Creating new from template for
more details
The last two are characteristics of ndarrays - in order to support things like array slicing. The complications of
subclassing ndarray are due to the mechanisms numpy has to support these latter two routes of instance creation.
2.8.3 View casting
View casting is the standard ndarray mechanism by which you take an ndarray of any subclass, and return a view of
the array as another (specified) subclass:
>>> import numpy as np
>>> # create a completely useless ndarray subclass
>>> class C(np.ndarray): pass
>>> # create a standard ndarray
>>> arr = np.zeros((3,))
>>> # take a view of it, as our useless subclass
>>> c_arr = arr.view(C)
>>> type(c_arr)
<class ’C’>
2.8. Subclassing ndarray 35