0

Python newbie here, would appreciate some help with multiple inheritance!

Consider the following class hierarchy:

class Base1:
    def display(self):
        print('Base1')

class Base2:
    def display(self):
        print('Base2')

class Derived1 (Base1):
    def display(self):
        super().display()
        print('Derived1')

class Derived2 (Base2):
    def display(self):
        super().display()
        print('Derived2')

class Derived (Derived1, Derived2):
    def display(self):
        super().display()
        print('Derived')

Derived().display()

I was expecting that the output of this would print the names of all the classes involved in the hierarchy, but it's not so. Further, if I add super().display() to both Base1 and Base2, I get the error AttributeError: 'super' object has no attribute 'display'.

What's wrong?

ankush981
  • 5,159
  • 8
  • 51
  • 96

1 Answers1

2

The classes Base1 and Base2 implicitly inherit from object which has no display method. This explains the AttributeError: 'super' object has no attribute 'display' exception.

The output of this code should be:

Base1
Derived1
Derived

When inheriting from multiple classes, they are searched from left to right for attributes when super is called. Thus, display is found on Derived1, so Derived2 is not looked at during the method resolution. See this question for more information.

Community
  • 1
  • 1
Jared Goguen
  • 8,772
  • 2
  • 18
  • 36
  • Thanks. Does that mean an inheritance loop has to be "closed" in order for `super()` to call methods from all classes? In this case, does that mean I add `display()` to `object`? – ankush981 Jan 20 '16 at 02:19
  • 2
    Uhh, adding methods to `object` is probably not recommended. It might be better for you to create your own objects from scratch, with the base object having a `display` method. It's hard to say without real code examples. Keep in mind that a lot of things inherit from `object` (i.e. all non-primatives), so you don't really want to monkey-patch it as it is likely to cause unforeseen consequences. – Jared Goguen Jan 20 '16 at 04:49
  • 1
    One important takeaway for me was that `super()` must not be present in root class. – ankush981 Jan 21 '16 at 16:30