使用Python C/API,如何使用普通Python类创建机制(即:不是扩展类型)创建普通Python类?
换句话说,PythonC/API与语句的等价性是什么(从某种意义上说,它在所有情况下都完全相同)

class X(bases):
    ...some methods/attributes here...

最佳答案

在Python中,可以通过调用内置函数以编程方式创建类。例如,请参见this answer
这需要三个参数:一个名称、一个基元组和一个字典。
您可以在C api中获得Pythontype作为type。然后你只需要使用one of the standard methods for calling PyType_Type callables调用它:

// make a tuple of your bases
PyObject* bases = PyTuple_Pack(0); // assume no bases
// make a dictionary of member functions, etc
PyObject* dict = PyDict_New(); // empty for the sake of example
PyObject* my_new_class = PyObject_CallFunction(&PyType_Type,"sOO",
                                             "X", // class name
                                             bases,
                                             dict);
// check if null

// decref bases and dict
Py_CLEAR(bases);
Py_CLEAR(dict);

(注意,您必须执行PyObject*-文档表明它是&PyType_Type但不是!)

07-27 23:01