How to tell which subclass was used to instantiate object

Frank Millman frank at chagford.com
Mon May 3 05:59:11 EDT 2004


frank at chagford.com (Frank Millman) wrote in message news:<246a4e07.0405012300.4776f4f3 at posting.google.com>...
> "John Roth" <newsgroups at jhrothjr.com> wrote in message news:<10978dla4s8sq17 at news.supernews.com>...
> > "Frank Millman" <frank at chagford.com> wrote in message
> > news:246a4e07.0405010447.11ed5400 at posting.google.com...
> > > Hi all
> > >
> > > I have a question regarding inheritance. I have come up with a
> > > solution, but it is not very elegant - I am sure there is a more
> > > pythonic approach. Assume the following class definitions.
> > >
>  [...]
> > >
> > > Is there a more direct way for a top-level class to determine which
> > > subclasses were used to instantiate it?
> > 
> > Look at the __class__ attribute. Specifically, __class__.__name__
> > should tell you the name of the class.
> > 
> > John Roth
> > >
> 
> Thanks for the reply, John. Unfortunately this does not seem to give
> me what I am looking for. I can only look at the __class__ attribute
> once the object has been instantiated.
> 
My apologies, John. You are quite correct, and I am talking rubbish.

The following are all accessible either during init() or after
instantiation -

__class__ is the class object.

__class__.__name__ is the name of the class.

__class__.__bases__ is a tuple containing the base classes of the
class. At first, I thought that the tuple would contain the
inheritance hierarchy, but on experimenting I see that, if you use
multiple inheritance, it contains all the classes used to define this
class. As I am not using multiple inheritance, the tuple will contain
1 or 0 elements. If you need the full hierarchy, you can walk through
the __bases__ tuples until you reach an empty tuple.

__class__.__bases__[0].__name__ is the name of the class that this
class has been inherited from, which is exactly what I am looking for.

Thanks for pointing me in the right direction.

Frank



More information about the Python-list mailing list