Python C API中的多重继承 [英] Multiple Inheritance in Python C API

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

问题描述

如何使用从多个其他类型继承的Python C API创建类型?

How do I create a type using the Python C API that inherits from multiple other types?

Python文档提供了一个从另一种类型继承的类型的示例,但是没有找到任何示例或提及多重继承.

The Python documentation includes an example of a type that inherits from one other type, but there is no example or mention of multiple inheritance I could find.

推荐答案

假设您有一个名为test的模块,其中包含以下类:

Let's say you have a module named test, with the following classes:

class A:
    a = 1

class B:
    b = 2

想法是创建一个新类C,该类继承自AB:

And the idea is to create a new class C which inherits from A and B:

import test

class C(test.A, test.B):
    pass

关于PyTypeObject.tp_base的规范表示它不支持多个基类,您必须创建类通过调用元类型" .在这种情况下,元类型为 type ,因此该类可以这样创建:

The specification on PyTypeObject.tp_base says that it does not support multiple bases classes and that you have to create the class "by calling the metatype". In this case, the metatype is type, so the class can be created this way:

from test import A, B

C = type("C", (A, B), {})

将其翻译为 C 很简单,尽管有点冗长:

Translating that to C is straightforward, although a bit verbose:

// from test import A, B
PyObject* test_module = PyImport_ImportModuleNoBlock("test");
if (test_module == NULL) return NULL;
PyObject* ClassA = PyObject_GetAttrString(test_module, "A");
if (ClassA == NULL) return NULL;
PyObject* ClassB = PyObject_GetAttrString(test_module, "B");
if (ClassB == NULL) return NULL;

// name, bases, classdict = "C", (A, B), {}
PyObject *name = PyUnicode_FromString("C");
if (name == NULL) return NULL;
PyObject *bases = PyTuple_Pack(2, ClassA, ClassB);
if (bases == NULL) return NULL;
PyObject *classdict = PyDict_New();
if (dict == NULL) return NULL;

// C = type(name, bases, classdict)
PyObject *ClassC = PyObject_CallObject(
    (PyObject*)&PyType_Type, PyTuple_Pack(3, name, bases, classdict));
if (ClassC == NULL) return NULL;
if (PyModule_AddObject(m, "C", ClassC)) return NULL;

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

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