Search code examples
pythonpython-3.xmultiple-inheritance

Traverse up to base class


I can do the following to get the name of the class I am using with an instance:

self.__class__.__name__

Is there a way to get the base class name without going beyond into any of the django built-in types? If so, how could that be done? For example if I have:

class Wire:
    def __init__(self, default=True):
        self.state = default
        self.observers = []


class LED(Wire):
    """
    For debugging."""

How could I get (without knowing how many levels of inheritance there might be)?:

>>> l = LED()
>>> l.get_base_case() # 'Wire'

Solution

  • You can use mro() on the object's type:

    type(l).mro()[1]  # 0: the type itself, 1: base class in linear hierarchy, ...
    

    Here mro stands for method resolution order.