how to get derived class name from base class

后端 未结 6 689
既然无缘
既然无缘 2020-12-29 18:35

I have a base class Person and derived classes Manager and Employee. Now, what I would like to know is the object created is Man

6条回答
  •  天命终不由人
    2020-12-29 19:32

    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.

提交回复
热议问题