Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it necessary to call super().__init__() explicitly in python?

I came from Java where we can avoid calling super class zero-argument constructor. The call to it is generated implicitly by the compiler.

I read this post about super() and now in question about is it really necessary to do something like this explicitly:

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

class B(A):
 def __init__(self):
   print("hello")
   super().__init__() #Do we get some Undefined Behavior if we do not call it explicitly?
like image 462
Some Name Avatar asked Feb 06 '26 14:02

Some Name


1 Answers

If you override the __init__ method of the superclass, then the __init__ method of the subclass needs to explicitly call it if that is the intended behavior, yes.

Your mental model of __init__ is incorrect; it is not the constructor method, it is a hook which the constructor method calls to let you customize object initialization easily. (The actual constructor is called __new__ but you don't need to know this, and will probably never need to interact with it directly, let alone change it.)

like image 153
tripleee Avatar answered Feb 08 '26 05:02

tripleee