81
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)?

martineau
  • 119,623
  • 25
  • 170
  • 301
Francis.TM
  • 1,761
  • 1
  • 18
  • 19
  • 2
    you better off to check http://stackoverflow.com/questions/961048/get-class-that-defined-method-in-python – okm Apr 10 '12 at 16:16
  • 3
    I don't think this question is a duplicate... at least not of the one that it points to. Like not in any way. My solution to this question: self.__class__.__mro__[1].__name__ – DonkeyKong Oct 25 '19 at 16:59

3 Answers3

101

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
trss
  • 915
  • 1
  • 19
  • 35
Jeremy Brown
  • 17,880
  • 4
  • 35
  • 28
72

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.

Mark Amery
  • 143,130
  • 81
  • 406
  • 459
vartec
  • 131,205
  • 36
  • 218
  • 244
  • 9
    +1 for this, [`mro()`](http://docs.python.org/library/stdtypes.html?highlight=mro#class.__mro__) is also useful – okm Apr 10 '12 at 16:24
  • 3
    MRO is Method Resolution Order. check here e.g. https://stackoverflow.com/questions/1848474/method-resolution-order-mro-in-new-style-classes – Chris Feb 23 '18 at 15:18
-7

You could change

return self.__class__

return A().__class__

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

Tom
  • 9