How to Invoke the Super Constructor in Python?

DDD
Release: 2024-11-17 17:21:02
Original
128 people have browsed it

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

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

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template