开发者

Python: unable to inherit from a C extension

开发者 https://www.devze.com 2022-12-25 19:53 出处:网络
I am trying to add a few extra methods to a matrix type from the pysparse library. Apart from that I want the new class to behave exactly like the original, so I chose to implement the changes using i

I am trying to add a few extra methods to a matrix type from the pysparse library. Apart from that I want the new class to behave exactly like the original, so I chose to implement the changes using inheritance. However, when I try

from pysparse import开发者_JAVA技巧 spmatrix

class ll_mat(spmatrix.ll_mat):
    pass

this results in the following error

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

What is this causing this error? Is there a way to use delegation so that my new class behaves exactly the same way as the original?


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

You could try to generate an object from this and then inherit from that object's type:

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

be aware, though, that it's quite feasible for a built-in type to declare it won't support being subclassed (this could be done even just to save some modest overhead); if that's what that type does, then you can't subclass it, and will 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消