How to examine the inheritance of a class?

Chris Rebert clp at rebertia.com
Thu Oct 23 21:56:48 EDT 2008


On Thu, Oct 23, 2008 at 6:36 PM, John Ladasky <ladasky at my-deja.com> wrote:
> Hello again!
>
> Suppose that I have several subclasses which inherit from a base
> class, thus:
>
> class Foo(object):
>
> class Spam1(Foo):
>
> class Spam2(Foo):
>
> class Spam3(Foo):
>
> etc.  The list of subclasses is not fully defined.  It is supposed to
> be extensible by the user.
>
> Many methods will differ between these classes.  However, there are
> operations which may be performed between two Foo objects, OR between
> any of Foo's derivatives.
>
> There are instances where I would like to perform type checking before
> carrying out the operation.  Rather than having to enumerate all of
> Foo's subclasses (which would defeat my intent of extending the list
> of subclasses anyway), I would like to see whether a class is DERIVED
> from Foo.  Where is this information stored in the class definition?

In __bases__, e.g. Spam1.__bases__, which would be (<class '__main__.Foo'>,).
In practice, you probably just want to use  if isinstance(some_obj,
Foo):  which will be true for SpamN instances.

Cheers,
Chris
-- 
Follow the path of the Iguana...
http://rebertia.com

>
> Thanks!
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>



More information about the Python-list mailing list