Jimmy C Jimmy C - 4 months ago 6x
Python Question

Inherit from scipy.sparse.csr_matrix class

I want to augment the

class with a few methods and replace a few others for personal use. I am making a child class which inherits from
, as such:

class SparseMatrix(sp.csr_matrix):
def __init__(self, matrix):
super(type(self), self).__init__(matrix)

This won't work though, throwing:

AttributeError: toSpa not found

Could you please explain to me what I'm doing wrong?


Somewhere in the SciPy Sparse Matrix implementation the first three letters of the class name are used to define a method that will do the transformations among the different sparse matrix types (see this thread). Therefore, you have to implement using a name like:

import numpy as np
from scipy.sparse import csr_matrix

class csr_matrix_alt(csr_matrix):
    def __init__(self, *args, **kwargs):
        super(csr_matrix_alt, self).__init__(*args, **kwargs)

s = csr_matrix_alt(np.random.random((10, 10)))
#<class '__main__.csr_matrix_alt'>

Other names like csr_mymatrix, csr_test and so forth would be possible...