12

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?
Some Name
  • 8,555
  • 5
  • 27
  • 77

1 Answers1

19

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.)

tripleee
  • 175,061
  • 34
  • 275
  • 318