温馨提示×

python子类调用父类的方法是什么

小亿
85
2023-12-05 00:29:06
栏目: 编程语言
Python开发者专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在Python中,子类可以通过使用super()函数来调用父类的方法。super()函数返回一个临时对象,该对象允许你调用父类的方法。你可以通过在子类中使用super()函数来调用父类的方法,并提供必要的参数。

下面是一个示例:

class ParentClass:
    def __init__(self):
        self.name = "Parent"

    def say_hello(self):
        print("Hello from Parent")

class ChildClass(ParentClass):
    def __init__(self):
        super().__init__()
        self.age = 10

    def say_hello(self):
        super().say_hello()  # 调用父类的say_hello方法
        print("Hello from Child")

child = ChildClass()
child.say_hello()

输出结果为:

Hello from Parent
Hello from Child

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读:python子类怎么调用父类方法

0