And Now Something Completely Different …

I finally figured out how to implement classes in Python using C API — the right way. Namely as a new type using the PyTypeObject complete with get and set attribute calls and plain members. But I tought my previous hack for building a class at runtime is still slim enough to share, especially if you just got a couple of methods that you want bundled into a class instead of a module.

The following function is very similar to the Py_InitModule(char*, PyMethodDef*) except that it returns a class object instead of a module object. Remember that the first argument to your methods will be an instance object of the class, and that you can include a method named __init__ just like in any regular Python class definition.

  1. inline PyObject*
  2. Py_InitClass(char* Name, PyMethodDef* Methods)
  3. {
  4. PyObject* classDict = PyDict_New();
  5. PyObject* className = PyString_FromString(Name);
  6. PyObject* classObject = PyClass_New(NULL, classDict, className);
  7.  
  8. PyMethodDef* def;
  9. for (def = Methods; def->ml_name != NULL; def++)
  10. {
  11. PyObject* func = PyCFunction_New(def, NULL);
  12. PyObject* method = PyMethod_New(func, NULL, classObject);
  13. PyDict_SetItemString(classDict, def->ml_name, method);
  14. }
  15.  
  16. return classObject;
  17. }
This entry was posted in Tutorials and tagged , , , . Bookmark the permalink. Both comments and trackbacks are currently closed.