Get parent class name?

PythonOop

Python Problem Overview


class A(object):
    def get_class(self):
        return self.__class__

class B(A):
    def __init__(self):
        A.__init__(self)

b = B()
print b.get_class()

This code will print <class '__main__.B'>.

How can I get the class name where the method has been defined (namely A)?

Python Solutions


Solution 1 - Python

From the documentation: https://docs.python.org/2/reference/datamodel.html#the-standard-type-hierarchy

Class objects have a __name__ attribute. It might cleaner to introspect the base class(es) through the __bases__ attr of the derived class (if the code is to live in the derived class for example).

>>> 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

Solution 2 - Python

> inspect.getmro(cls) > > Return a tuple of class cls’s base classes, > including cls, in method resolution order. No class appears more than > once in this tuple. Note that the method resolution order depends on > cls’s type. Unless a very peculiar user-defined metatype is in use, > cls will be the first element of the tuple.

import inspect
inspect.getmro(B)

result will be:

(<class '__main__.B'>, <class '__main__.A'>, <type 'object'>)

First element is the class itself, second element is always first of the parents. After that things can get bit more complicated.

Solution 3 - Python

You could change

return self.__class__

return A().__class__

Since there is no other instance of A() available...

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionFrancis.TMView Question on Stackoverflow
Solution 1 - PythonJeremy BrownView Answer on Stackoverflow
Solution 2 - PythonvartecView Answer on Stackoverflow
Solution 3 - PythonTomView Answer on Stackoverflow