Super() function is used to call a method from a parent class in a method resolution order (MRO). When a class is derived from multiple parent classes (like in the case of class D), the MRO defines the order in which Python searches for the method when it encounters a method call.
Let's break down the control flow step by step to understand the output:
- You create an object obj of class D.
- When you call obj.test(), Python starts looking for the test() method in the class hierarchy of D according to the MRO.
- Since D inherits from both B and C, Python follows the MRO, which, in this case, is D -> B -> C -> A.
- Python finds the test() method in class B first. So, it executes the test() method of class B.
- Inside the test() method of class B, you have super(B, self).test(). Here, super(B, self) means "call the method of the parent class of B (i.e., A)". So, Python executes the test() method of class A.
Now let's examine the order of the print statements:
- "test of B called" is printed when the test() method of class B is executed.
- "test of C called" is printed from super(B, self).test(), which calls the test() method of class C.
- "test of A called" is printed from super(C, self).test(), which calls the test() method of class A.
So, the final output is:
test of B called
test of C called
test of A called
It's essential to understand the method resolution order and how super() works, especially in cases where a class inherits from multiple parent classes, as the order of execution can be critical in achieving the desired behavior.