Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting all superclasses in Python 3

How I can get a list with all superclasses of given class in Python?

I know, there is a __subclasses__() method in inspent module for getting all subclasses, but I don't know any similar method for getting superclasses.

like image 947
VeLKerr Avatar asked Jun 24 '15 13:06

VeLKerr


1 Answers

Use the __mro__ attribute:

>>> class A:
...     pass
...
>>> class B:
...     pass
...
>>> class C(A, B):
...     pass
...
>>> C.__mro__
(<class '__main__.C'>, <class '__main__.A'>, <class '__main__.B'>, <class 'object'>)

This is a special attribute populated at class instantiation time:

class.__mro__ This attribute is a tuple of classes that are considered when looking for base classes during method resolution.

class.mro() This method can be overridden by a metaclass to customize the method resolution order for its instances. It is called at class instantiation, and its result is stored in __mro__.

like image 160
jonrsharpe Avatar answered Nov 15 '22 16:11

jonrsharpe