Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Python why is calling super() function for a class with no superclass defined is not an error? [duplicate]

Tags:

python

For a Python novice, please can someone tell me what is happening here? Why is it printing "A init"?

If i remove the line super().__init__() from __init__ function of class B then the behaviour is as expected. But why is below code not an error, I though B would not have a superclass??

class A:

    def __init__(self):
        print("A init")

class B:

    def __init__(self):
        super().__init__()   # why is this line not an error
        print("B init")

class C(B, A):

    def __init__(self):
        super().__init__()
        print("C init")

c = C()

Output

A init

B init

C init

Process finished with exit code 0
like image 435
zeitgeist Avatar asked Mar 08 '26 05:03

zeitgeist


1 Answers

You create an instance of C, which we'll call self. It has an MRO of C, B, A, object.

C's __init__ first calls super().__init__(). This delegates to the __init__ in the next class in the MRO, which is B, using the same self object.

B's __init__ first calls super().__init__(). This delegates to the __init__ in the next class in the MRO of self's class (C), which is A.

A's __init__ prints and returns to B's __init__.

B's __init__ prints and returns to C's __init__.

C's __init__ prints and returns to the constructor (object's __new__), which returns self.

super() has two hidden arguments, __class__ (so it knows where to start from in the MRO), and self (or cls, for @classmethods—it's whatever the first argument is, regardless of name).

You had to provide these explicitly in Python 2 (and still can), but in Python 3 super() actually inspects the stack frame of its caller and finds these when called from inside a method. (The __class__ variable is implicitly available inside methods, and is the class it was defined in.)

like image 104
gilch Avatar answered Mar 09 '26 17:03

gilch