Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get name of derived class from base class

I can get the name of a base class as follows:

>>> class Base(object):
...     pass
...
>>> class Derived(Base):
...     def print_base(self):
...         for base in self.__class__.__bases__:
...             print base.__name__
...
>>> foo = Derived()
>>> foo.print_base()
Base

In this example, how do I do the reverse and get the name of Derived from a function within Base? E.g:

>>> class Base(object):
...     def print_derived(self):
...         [pseudocode: return Derived class name]
...
>>> class Derived(Base):
...     pass
...
>>> bar = Derived()
>>> bar.print_derived()
Derived

I could obviously just print self.__class__.__name___ in Derived but I have a lot of unit tests inheriting Base as a mixin and I want to track which class called it from one adjustment to the Base mixin.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You just need to print self.__class__ in the Base method:

>>> class Base(object):
...     def print_derived(self):
...         print(self.__class__.__name__)
...
>>> class Derived(Base):
...     pass
>>> d = Derived()
>>> d.print_derived()
Derived
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading