Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
664 views
in Technique[技术] by (71.8m points)

inheritance - Python: unable to inherit from a C extension

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 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...