[Numpy-discussion] subclassing matrix

Basilisk96 basilisk96 at gmail.com
Sat Jan 12 22:59:20 EST 2008


Thanks Stefan and Colin,

The subclass documentation made this a little clearer now. Instead of
using a super() call in __new__, I now do this:

    #construct a matrix based on the input
    ret = _N.matrix(data, dtype=dtype)
    #promote it to Vector
    ret = ret.view(cls)

The second statement there also invokes a call to __array_finalize__,
which ensures that the Format attribute is attached to the instance.
Then I validate and manipulate the shape of the matrix so that it is a
(3,1) vector. Now the instance builder is proper.

my __array_finalize__ looks like this:

    def __array_finalize__(self, obj):
        self.Format = getattr(obj, "Format", FMT_VECTOR_DEFAULT)
        return

Also, after learning about the view method, I am now doing the
following in Vector.cross:

    def cross(self, other):
        """Cross product of this vector and another vector"""
        #calling the result's view method promotes it to Vector
        result = _N.cross(self, other, axis=0)
        result = result.view(type(self))
        return result

It also works if I just use Vector(...), but it is my gut feeling that
invoking a view vs. instantiating a new Vector instance is cheaper?

Now I can add more unit tests.

Cheers,
-Basilisk96



More information about the NumPy-Discussion mailing list