how to get derived class name from base class
I don't know if this is what you want, and the way you'd like it implemented, but here's a try:
>>> class Person(object): def _type(self): return self.__class__.__name__>>> p = Person()>>> p._type()'Person'>>> class Manager(Person): pass>>> m = Manager()>>> m._type()'Manager'>>>
Pros: only one definition of the _type
method.
You can use x.__class__.__name__
to retrieve the class name as a string, e.g.
class Person: passclass Manager(Person): passclass Employee(Person): passdef get_class_name(instance): return instance.__class__.__name__>>> m = Manager()>>> print get_class_name(m)Manager>>> print get_class_name(Employee())Employee
Or, you could use isinstance to check for different types:
>>> print isinstance(m, Person)True>>> print isinstance(m, Manager)True>>> print isinstance(m, Employee)False
So you could do something like this:
def handle_person(person): if isinstance(person, Manager): person.read_paper() # method of Manager class only elif isinstance(person, Employee): person.work_hard() # method of Employee class only elif isinstance(person, Person): person.blah() # method of the base class else: print "Not a person"
Python objects provide a __class__
attribute which stores the type used to make that object. This in turns provides a __name__
attribute which can be used to get the name of the type as a string. So, in the simple case:
class A(object): passclass B(A): passb = B()print b.__class__.__name__
Would give:
'B'
So, if I follow your question correctly you would do:
m = Manager()print m.__class__.__name__'Manager'