Search code examples
pythonpython-3.xinheritancesuperclass

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.


Solution

  • 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__.