Python:无法从C扩展继承 [英] Python: unable to inherit from a C extension

查看:279
本文介绍了Python:无法从C扩展继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从pysparse库向矩阵类型添加一些额外的方法。除此之外,我希望新类的行为与原始类完全相同,因此我选择使用继承来实现更改。但是,当我从pysparse import spmatrix尝试

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

这会导致以下错误

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 被记录为函数 - 不是类型本身。这个成语被称为工厂函数 - 它允许创建者可调用根据其参数返回不同的实际底层类型。

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)

等等。

这篇关于Python:无法从C扩展继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆