简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM