what will happen if i call a child class method from base class init in python

#11
by smangrul - opened

Question:

what will happen if i call a child class method from base class init in python

Answer:

There are a few things that you should take into consideration:

  1. The order of the calls to super can be crucial, since super() is a function. You should use super() at the right place in the code.

  2. It is always a good idea to use super() instead of super(super) (see What is the super() technique and why is it used instead of super()?).

  3. super() is always called at the highest possible level. You should not try to use super() in a parent class.

  4. The super() keyword does not work with __init__() methods (unless you do something strange with the super() argument).

Here is an example to explain what I mean:

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

class B(A):
def init(self):
print("B")

class C(B):
def init(self):
print("C")

B and C have the same order

b = B()
c = C()

A and C have the same order

a = A()
c = C()

B and C have the same order

b = B()
a = A()

Here is a table showing the expected results:

A
B
C
A
B
C


If we change the order of the super() calls, we get the following results:

A
B
C
A
B
C


The reason why A is printed before B and C is that it is called before B.

The reason why B is printed before C is that it is called before C.

The reason why C is printed before A is that it is called before A.


Important: This is just a simple example to explain the problem. In your case, it may be different.


I have no idea what your code is doing, but I would suggest that you do not use super() as you do. If you use it correctly, it should work…

Sign up or log in to comment