如何将C方法附加到现有的Python类?

此方法显示如何从C扩展模块定义新的Python类。该类的方法在C中实现,但是仍可以从Python实例化,子类化和扩展该类。带有继承的相同技术也可以用于扩展现有的Python类,并使用C语言编写的方法。在该技术中,PyClass_New的第一个参数作为NULL传递,表明新类没有基类。然后,我们在该位置传递基类的元组,即使我们的新类是在C扩展而不是Python源代码中构建的,我们也将获得正常的Python继承行为。

示例

#include <Python.h>
static PyObject* Foo_init(PyObject *self, PyObject *args)
{
    printf("Foo._ _init_ _ called\n");
    Py_INCREF(Py_None);
    return Py_None;
}
static PyObject* Foo_doSomething(PyObject *self, PyObject *args)
{
    printf("Foo.doSomething called\n");
    Py_INCREF(Py_None);
    return Py_None;
}
static PyMethodDef FooMethods[] =
{
    {"_ _init_ _", Foo_init, METH_VARARGS, "doc string"},
    {"doSomething", Foo_doSomething, METH_VARARGS, "doc string"},
    {0, 0},
};
static PyMethodDef ModuleMethods[] = { {0, 0} };
#ifdef _ _cplusplus
extern "C"
#endif
void initFoo(  )
{
    PyMethodDef *def;
    /* create new module and class objects */
    PyObject *module = Py_InitModule("Foo", ModuleMethods);
    PyObject *moduleDict = PyModule_GetDict(module);
    PyObject *classDict = PyDict_New(  );
    PyObject *className = PyString_FromString("Foo");
    PyObject *fooClass = PyClass_New(NULL, classDict, className);
    PyDict_SetItemString(moduleDict, "Foo", fooClass);
    Py_DECREF(classDict);
    Py_DECREF(className);
    Py_DECREF(fooClass);
    /* add methods to class */
    for (def = FooMethods; def->ml_name != NULL; def++) {
        PyObject *func = PyCFunction_New(def, NULL);
        PyObject *method = PyMethod_New(func, NULL, fooClass);
        PyDict_SetItemString(classDict, def->ml_name, method);
        Py_DECREF(func);
        Py_DECREF(method);
    }
}