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

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

Linda Hamilton
Release: 2024-11-18 00:07:02
Original
888 people have browsed it

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__()
Copy after login

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__()
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template