[SciPy-user] sequence emulation -/-> array access?

Travis Oliphant oliphant.travis at ieee.org
Sat Dec 17 18:58:43 CST 2005

Dan Christensen wrote:

>In more detail, I'd like to override + and * on arrays, but allow them
>to be used in other ways as standard arrays, e.g. innerproduct(a,b)
>should do the usual thing.
Well, internally innerproduct does not use the generic + and * operator 
to do the computation unless the type of the array is *object*.

So, you should be able to subclass rather easily.   The only confusion, 
perhaps, is that the array function *is not* a __new__ method.  The 
ndarray.__new__ method has arguments that are slightly different.  There 
are basically two ways to create an array (as an empty array or from a 
buffer).  The docstring of ndarray has more information in newer 
versions:  help(ndarray).  Also,   look at matrix.py, chararray.py, 
records.py, and memmap.py for examples of how to subclass.

Basically, you need to define the __new__ method (the only thing that's 
necessary, no __init__ is needed).   Then define __mul__ and __add__ the 
way you want.

from scipy import ndarray

class mysub(ndarray):
    def __new__(self, *args):
          #you need to call ndarray.__new__ in here with one of two sets 
of arguments

    def __mul__(self, other):
          # do what you want

    def __add__(self, other):
          # do what you want.

If you want to define an __array_finalize__ method it will be called 
every time a new object of your class is created so you can keep meta 
information consistent.  This is what the matrix class does to enforce a 
2-dimensional array all the time.


More information about the SciPy-user mailing list