首页 >后端开发 >Python教程 >Python中如何调用超级构造函数?

Python中如何调用超级构造函数?

DDD
DDD原创
2024-11-17 21:35:02692浏览

How Do You Invoke the Super Constructor in Python?

在Python中调用超级构造函数

问题中提到“其他语言”表明询问者熟悉面向对象( OO)用其他语言编程,通常情况是隐式调用基(超)类构造函数。 Python 中也是如此,虽然有显式调用超类构造函数的方法。

为了满足查询者的期望,Python 3 简化了调用超类构造函数的过程。以下示例提供了在 Python 3 中工作的显式演示:

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

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

在 Python 2 中,调用超类构造函数需要稍微更详细的形式:

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

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

两个示例都输出 " hello”后跟“world”,演示了超类构造函数的正确调用。

以上是Python中如何调用超级构造函数?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn