1

I'm new to concept of super.I'm unable to understand the call stack made by m method of each class in this code

class A:
    def m(self):
        print("m of A called")
        print("OUT OF A")

class B(A):
    def m(self):
        print("m of B called")
        super().m()
        print("OUT OF B")

class C(A):
    def m(self):
        print("m of C called")
        super().m()
        print("OUT OF C")

class D(B,C):
    def m(self):
        print("m of D called")
        super().m()
        print("OUT OF D")

x = D()
x.m()

Output of following is:

m of D called
m of B called
m of C called
m of A called
OUT OF A
OUT OF C
OUT OF B
OUT OF D

How is super from D calling B.() and C.() which calls A.m() only once

1 Answers1

0

The explanation can be found here: https://docs.python.org/3.6/library/functions.html#super

Basically you get the EITHER the super class or sibling (with multiple inheritance)

from the link:

The second use case is to support cooperative multiple inheritance in a dynamic execution environment. This use case is unique to Python and is not found in statically compiled languages or languages that only support single inheritance. This makes it possible to implement “diamond diagrams” where multiple base classes implement the same method. Good design dictates that this method have the same calling signature in every case (because the order of calls is determined at runtime, because that order adapts to changes in the class hierarchy, and because that order can include sibling classes that are unknown prior to runtime).

LhasaDad
  • 1,786
  • 1
  • 12
  • 19