溫馨提示×

python子類調用父類的方法是什么

小億
98
2023-12-05 00:29:06
欄目: 編程語言

在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

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女