Home  >  Article  >  Backend Development  >  How Does the `super()` Constructor Work in Python?

How Does the `super()` Constructor Work in Python?

Linda Hamilton
Linda HamiltonOriginal
2024-11-18 00:07:02822browse

How Does the `super()` Constructor Work in Python?

Invoking Super Constructors in Python

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn