Home  >  Article  >  Backend Development  >  How to Invoke the Super Constructor in Python?

How to Invoke the Super Constructor in Python?

DDD
DDDOriginal
2024-11-17 17:21:02130browse

How to Invoke the Super Constructor in Python?

Invoking the Super Constructor in Python

Unlike other programming languages, Python does not implicitly invoke the super constructor. This raises the question of how to explicitly invoke the super constructor in Python.

Python 3

To invoke the super constructor in Python 3, simply use the super().__init__() syntax within the subclass constructor:

class A(object):
    def __init__(self):
        print("world")

class B(A):
    def __init__(self):
        print("hello")
        super().__init__()

Python 2

In Python 2, a slightly more verbose syntax is required:

class A(object):
    def __init__(self):
        print "world"

class B(A):
    def __init__(self):
        print "hello"
        super(B, self).__init__()

This super(B, self) syntax is equivalent to super() in Python 3. Remember to include the object base class to explicitly specify that your classes are old-style classes.

The above is the detailed content of How to Invoke the Super Constructor 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