Spaces:
Runtime error
what will happen if i call a child class method from base class init in python
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:
-
The order of the calls to
super
can be crucial, sincesuper()
is a function. You should usesuper()
at the right place in the code. -
It is always a good idea to use
super()
instead ofsuper(super)
(see What is the super() technique and why is it used instead of super()?). -
super()
is always called at the highest possible level. You should not try to usesuper()
in a parent class. -
The
super()
keyword does not work with__init__()
methods (unless you do something strange with thesuper()
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…