0

I am unable to understand this code snippet.

class First():  
  def __init__(self):  
    super(First, self).__init__()  
    print("first")  

class Second():  
  def __init__(self):  
    super(Second, self).__init__()  
    print("second")  

class Third(Second, First):  
  def __init__(self):  
    super(Third, self).__init__()  
    print("third")  

Third(); 

and the output is :

first  
second  
third  

It seems that constructor of each is called in reverse order of base classes First.__init__() then Second.__init__()
How is super(Third, self).__init__() this statement working.

adi K
  • 1
  • 4

1 Answers1

1

You called super() before you print, so yes, only after super() returns will your print() expressions be reached.

Your class Method Resolution Order (MRO) is:

>>> Third.__mro__
(<class '__main__.Third'>, <class '__main__.Second'>, <class '__main__.First'>, <class 'object'>)

so creating Third() then results in:

Third.__init__()
    super(Third, self).__init__()
        Second.__init__()                   # next in the MRO for Third
            super(Second, self).__init__()
                First.__init__()            # next in the MRO for Third
                    super(First, self).__init__()
                        object.__init__()   # next in the MRO for Third
                            return
                    print("first")
                    return
            print("second")
            return
    print("third")
    return

so the code outputs first, second, then third, but the methods were called in the opposite order.

Side note: super() is a type of object, not a keyword. super() is just another expression (albeit one that causes some side effects during compilation).

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343