Python: cannot inherit from C extension

I am trying to add some additional methods to the matrix type from the pysparse library. Also, I want the new class to behave exactly the same as the original, so I decided to implement the changes using inheritance. However when i try

from pysparse import spmatrix class ll_mat(spmatrix.ll_mat): pass 

this leads to the following error

 TypeError: Error when calling the metaclass bases cannot create 'builtin_function_or_method' instances 

What is the reason for this error? Is there a way to use delegation so that my new class behaves exactly like the original?

+6
python inheritance
source share
1 answer

ll_mat documented as a function - not the type itself. The idiom is known as a "factory function" - it allows the "creator callable" to return different actual base types depending on their arguments.

You can try to generate an object from this and then inherit from this type of object:

 x = spmatrix.ll_mat(10, 10) class ll_mat(type(x)): ... 

remember, however, that it is possible for the built-in type to declare that it will not be subclassed (this can even be done to save some modest overhead); if this is what this type does, then you cannot subclass it and would rather have to use containment and delegation, i.e.:

 class ll_mat(object): def __init__(self, *a, **k): self.m = spmatrix.ll_mat(*a, **k) ... def __getattr__(self, n): return getattr(self.m, n) 

etc. etc.

+9
source share

All Articles