In the world of programming, the super constructor plays a crucial role in calling the parent class's constructor. As you mentioned, the expectation of using super() in Python might seem evident due to its familiarity from other programming languages. However, Python offers a slightly different approach to this invocation.
In Python 3 and beyond, the superclass constructor can be invoked using a simplified syntax:
class A(object): def __init__(self): print("world") class B(A): def __init__(self): print("hello") super().__init__()
This syntax replaces the previous longer form that was used in Python 2:
class A(object): def __init__(self): print "world" class B(A): def __init__(self): print "hello" super(B, self).__init__()
In Python 2, you had to specify the containing classname in the super() method call. However, in Python 3, the double underscore (__) syntax introduced a shortcut that allows you to omit this parameter, resulting in cleaner code.
The above is the detailed content of How Does the `super()` Constructor Work in Python?. For more information, please follow other related articles on the PHP Chinese website!