[SciPy-User] Subclassing scipy sparse matrix class

Per Nielsen evilper@gmail....
Wed Nov 30 03:01:27 CST 2011


Hi all

I am trying to create a subclass of the sparse matrix class in scipy, to
add some extra methods I need.

I have tried to follow the guide on: http://www.scipy.org/Subclasses but
without much luck, the view method does not exist for the sparse matrix
class. Below is a script I have created

-----------------

#!/usr/bin/env python

from scipy.sparse.csr import csr_matrix as spmatrix

class sparsematrix_addons(spmatrix):
    """
    subclass for standard scipy sparse class to add missing functionality
    """

    def __new__(cls, matrix):
        obj = spmatrix.__init__(cls, matrix)
        return obj

    def square_spmat(self, M):
        return M ** 2

    def ravel_spmat(self, M):
        pass

if __name__ == '__main__':

    import numpy as np

    x = (np.random.rand(10, 10) * 2).astype(int).astype(float)
    xsp = sparsematrix_addons(x)

--------------------

However, this generates the following error:

TypeError: unbound method __init__() must be called with csr_matrix
instance as first argument (got type instance instead)

I am not strong in python OOP, or OOP in general, so I am sure this is a
rather trivial problem to solve.

Anyone got any solutions or ideas to point me in the right direction?

Thanks in advance,

Per
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.scipy.org/pipermail/scipy-user/attachments/20111130/9ab90864/attachment.html 


More information about the SciPy-User mailing list