MRO (Method Resolution Order) in Python for this code

56 views Asked by At

I got this code:

class A:
    def gg(self):
        print ('Class A')
        
class B(A):
    def gg(self):
        print('First Class B')
        super().gg()
        print('Class B')
        
class C(A):
    def gg(self):
        print('First Class C')
        super().gg()
        print('Class C')
        
class D (B,C):
        
    def gg(self):
        print('First Class D')
        super().gg()
        print('Class D')

        
good = D()

good.gg()

The print expected in my opinion should be:

  1. "First Class D" as is the first element in the function
  2. "First Class B" as it goes through super and is the first element of the firt inherit class
  3. "Class A" as it goes through the second element (a super) of the first inherit class and this is the first element of the reinherit class
  4. "Class B" as it goes through the third element of the first inherit class
  5. "First Class C" as it goes though the first element of the second inherit class
  6. "Class A" as it goes through the second element (a super) of the second inherit class and this is the first element of the reinherit class
  7. "Class C" as it goes though the third element of the second inherit class
  8. "Class D" as it goes to the las element of the class

Instead, the print is this one:

First Class D
First Class B
First Class C
Class A
Class C
Class B
Class D

I do not understand any of this prints. Overall, what I do not understand is how it can go from "First Class B" to "First Class C" without passing through the prints "Class A" and "Class B". But what is even more difficult to understand is how can it goes from the prints "Class A" to "Class C" if I am inherting first the class B as we saw that the print 'First Class B" goes before "First Class C" and is not printing 'Class B' before 'Class C'. Also it will be nice if you explain why my expectations are wrong step by step

0

There are 0 answers