I\'ve been learning more about Python recently, and as I was going through the excellent Dive into Python the author noted here that the __init__
method is not tech
The difference is owing to Python's dynamic typing. Unlike C++ where variables are declared with types and allocated in memory, Python's variables are created when assigned at run time. C++ no-arg constructors are automatically called so that they can initialize data members. In Python, it is done on demand and __init__
is looked up by the inheritance tree, only the lowest one is called and once. If a superclass data attribute is needed, super().__init__()
is explicitly called like C++ initialization list. Below is an example where Base.s is initialized:
class Base:
def __init__(self, base):
print("Base class init called")
self.base = base
class Super(Base):
def __init__(self, base):
print("Super class init called")
#super(Super, self).__init__(base)
super().__init__(base)
class Sub(Super):
def __init__(self, base):
print("Default __init__ is called")
super().__init__(base)
sub = Sub({"base3": 3, "base4": 4})
print(sub.__dict__, sub.base)
Output:
Default __init__ is called
Super class init called
Base class init called
{'base': {'base3': 3, 'base4': 4}} {'base3': 3, 'base4': 4}
Also, init is just like an ordinary function and can be called afterwards as such:
Sub.__init__(sub, 'abc')
print(sub.__dict__, sub.base)
Output:
Default __init__ is called
Super class init called
Base class init called
{'base': 'abc'} abc