How Do You Invoke the Super Constructor in Python?

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

How Do You Invoke the Super Constructor in Python?

Invoking the Super Constructor in Python

The reference to "other languages" in the question suggests that theinquirer is familiar with object-oriented (OO)programming in other languages, where it is typically thecase that the base(super) class constructor is invoked implicitly. This is also the case in Python, althoughthere are methods for explicitly invoking the superclassconstructor.

To address the inquirer's expectations, Python 3 has simplified the process of invoking the superclass constructor. The following example provides an explicit demonstration that works in Python 3:

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

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

In Python 2, invoking the superclass constructor requires a slightly more verbose form:

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

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

Both examples output "hello" followed by "world," demonstrating the correct invocation of the superclass constructor.

The above is the detailed content of How Do You 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