[Numpy-discussion] Superclassing numpy.matrix: got an unexpected keyword argument 'dtype'

Robert.Conde@sungar... Robert.Conde@sungar...
Wed Dec 10 06:15:37 CST 2008

I'm using numpy-1.1.1 for Python 2.3.  I'm trying to create a class that acts just like the numpy.matrix class with my own added methods and attributes.  I want to pass my class a list of custom "instrument" objects and do some math based on these objects to set the matrix.  To this end I've done the following:
from numpy import matrix

class rcMatrix(matrix):
    def __init__(self,instruments):
        """Do some calculations and set the values of the matrix."""
        self[0,0] = 100 # Just an example
        self[0,1] = 100 # The real init method
        self[1,0] = 200 # Does some math based on the input objects
        self[1,1] = 300 #
    def __new__(cls,instruments):
        """When creating a new instance begin by creating an NxN matrix of
        len_ = len(instruments)
        return matrix.__new__(cls,[[0.0]*len_]*len_)
It works great and I can, for example, multiply two of my custom matrices seamlessly.  I can also get the transpose.  However, when I try to get the inverse I get an error:
> rcm = rcMatrix(['instrument1','instrument2'])
> print rcm
[[ 100.  100.]
 [ 200.  300.]]
> print rcm.T
[[ 100.  200.]
 [ 100.  300.]]
> print [5,10] * rcm
[[ 2500.  3500.]]
> print rcm.I
Traceback (most recent call last):
  File "[Standard]/deleteme", line 29, in ?
  File "C:\Python23\Lib\site-packages\numpy\core\defmatrix.py", line 492, in getI
    return asmatrix(func(self))
  File "C:\Python23\Lib\site-packages\numpy\core\defmatrix.py", line 52, in asmatrix
    return matrix(data, dtype=dtype, copy=False)
TypeError: __init__() got an unexpected keyword argument 'dtype'


I've had to overwrite the getI function in order for things to work out:

    def getI(self): return matrix(self.tolist()).I
    I = property(getI, None, doc="inverse")

Is this the correct way to achieve my goals?
Please let me know if anything is unclear.
Robert Conde

More information about the Numpy-discussion mailing list