Subclassing in C

Iker Arizmendi iker at research.att.com
Mon Sep 13 18:56:14 EDT 2004


Hello all,

I've defined a class in a C extension module that is
(or rather, I would like to be) a subclass of another
class. I do this by simply setting the tp_base pointer
of my subclass's type object. However, this results
in a class that exposes the methods of the base class,
but ONLY those. The methods of my subclass are hidden.
I'd obviously like to have the methods of the base
class AND the new methods of the subclass available.

Here's the code snippet I used:

     static PyTypeObject MyPyType =
     {
        PyObject_HEAD_INIT(NULL)
        0,                   /* ob_size */
        "mymod.MyPyType",  /* tp_name */
        sizeof(MyPyType), /* tp_basicsize */
        ...
        (destructor)MyPyType_dealloc, /* tp_dealloc */
        ...
        Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
        ...
        MyPyType_methods, /* tp_methods */
        MyPyType_members, /* tp_members */
        ...
        (initproc)MyPyType_init, /* tp_init */
        0,                       /* tp_alloc */
        MyPyType_new,            /* tp_new */
     };


     PyMODINIT_FUNC initmymod(void)
     {
        MyPyType.tp_new = MyPyType_new;
        MyPyType.tp_base = pointerToOtherPyType;
        if (PyType_Ready(&MyPyType) < 0)
            return;
     }

When using MyPyType in python code, the methods defined in
MyPyType_methods are not visible. If I comment out the
line that sets tp_base then they become visible but the
base class methods are unavailable. What's the correct
way to do this sort of thing?

Regards,
Iker





More information about the Python-list mailing list