This method shows how to define a new Python class from a C extension module. The methods of the class are implemented in C, but the class can still be instantiated, subclassed, and extended from Python. The same technique with inheritance can also be used to extend an existing Python class with methods written in C. In this technique, the first argument to PyClass_New is passed as NULL, showing that the new class has no base classes. We then pass the tuple of base classes in this spot, and we will get normal Python inheritance behavior, even though our new class is being built in a C extension rather than in Python source code.
Example
#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); } }