Python Inheritance - A C example (without third party libraries)

Martin von Loewis loewis at informatik.hu-berlin.de
Wed May 16 13:10:57 EDT 2001


"Aaron Drew" <nospam at nospam.com> writes:

> I have even used Py_FindMethodInChain() to allow calling of base
> class functions but I can't find any good documention on the
> 'correct' way to do this.

There is no single 'correct' way; it is good when it works using only
documented API.

The traditional Python way is that C types are completely unrelated to
each other, so the wrapper around the derived class should duplicate
all code of the wrapper around the base type.

> For example, my system doesn't allow me to do typecasting from a
> derived type to a base class and I'm not entirely sure that using
> Py_FindMethodInChains() is 'correct' (ie. the standard way to do
> things).

What do you mean, 'does not allow to do typecasting'? There is no type
casting in Python, so you surely mean typecasting in C. Of the wrapper
objects, or of the C++ objects? Surely, if you have different structs
with object heads, pointers to them cannot be automatically converted
in C.

There is are a number of possible solutions, but you'll have to
identify the problem first before attempting a solution.

> The xxobject template doesn't demonstrate how to check that an object is a
> subclass of some other object. 

That's because Python C types are not subtypes of each other.

> I can implement (in C/C++) a system that will perform downcast
> checking for all of my C/C++ classes but that won't work when I pass
> in a derived class type that was written solely in python.

Are you saying that you have Python classes that inherit from C++ types?
Did you use extension classes? If not, how did you do that?

> I think I've found what I'm looking for anyway. There is a tuple called
> __bases__ that looks to store references to a classes base types. The
> attribute cl_bases of PyClassObject points to this tuple. If I use
> PyClassObject types for my wrappers and populate this tuple myself I think
> it might just fit in easily with the existing python class code. Is this
> right?

No. If you create instances of PyClassObject, you get class objects,
not wrappers around some C data structure. There is no inheritance
between Python C types, just trust us with that.

Regards,
Martin




More information about the Python-list mailing list