简体   繁体   English

如何在 C 扩展中继承 Python 类型?

[英]How to subclass Python types inside C extensions?

I know how to define a new type (class) in a Python extension, but is it also possible to define a class that is derived from a Python class? I know how to define a new type (class) in a Python extension, but is it also possible to define a class that is derived from a Python class? For example, in Python I could define an "extended" list class like so:例如,在 Python 中,我可以定义一个“扩展”列表 class,如下所示:

class xlist(list):
    def xsum(self):
        return sum(self)

How would I derive the xlist type from PyList inside a C extension?如何从 C 扩展中的 PyList 派生 xlist 类型? I wanted to try it out by declaring a PyTypeObject variable and memcpy()ing the contents of the PyList_Type instance into it, but I couldn't figure out how to add the "xsum" method to the new type.我想通过声明一个 PyTypeObject 变量并 memcpy() 将 PyList_Type 实例的内容放入其中来尝试一下,但我不知道如何将“xsum”方法添加到新类型中。

I thought I had read the whole doc about extensions.我以为我已经阅读了有关扩展的整个文档。 Turns out I hadn't.原来我没有。 It's all here. 都在这里。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM