Home > Back-end >  Multilevel and Multiple inheritance using super() in Python returns odd result
Multilevel and Multiple inheritance using super() in Python returns odd result

Time:05-02

if I type this this code,

class A:
    pass

class B(A):
    def show_letter(self):
        print("This is B")

class C(B):
    def show_letter(self):
        super().show_letter()
        print("This is C")

class E(B):
      def show_letter(self):
        super().show_letter()
        print("This is E")

class D(C, E):
    division = "North"

    def show_letter(self):
        super().show_letter()
        print("This is D")

div1 = D()
div1.show_letter()

it returns:

This is B
This is E
This is C
This is D

Why is there "E" printed ? If I delete super() in C class, "E" is not printed. Thank you.

CodePudding user response:

This is because the method resolution order. The first call is in D, then it calls C due to the arguments order: D(C, E). It could call B as parent but the latter is also a parent for E, so it is called the first. Only after that there is a B call. Thereby your call order is D -> C -> E -> B & the print order is revered.

  • Related