How to get name of derived class from base class
Question:
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.
Answers:
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
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.
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