共計 695 個字符,預計需要花費 2 分鐘才能閱讀完成。
在 Python 中,要調用父類的方法,可以使用 `super()` 函數來實現。
在子類中,通過 `super()` 函數可以調用父類的方法,從而實現對父類方法的重用。
`super()` 函數需要傳遞兩個參數:子類名和 self 對象。通過這兩個參數,`super()` 函數可以找到當前子類的父類,并調用父類中相應的方法。
以下是一個示例代碼:
“`python
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.name = “Child”
def say_hello(self):
super().say_hello() # 調用父類的方法
print(“Hello from Child”)
child = ChildClass()
child.say_hello()
“`
輸出結果為:
“`
Hello from Parent
Hello from Child
“`
在上述示例中,`ChildClass` 繼承自 `ParentClass`,在子類的 `__init__` 方法中通過 `super().__init__()` 調用了父類的構造方法,并在子類的 `say_hello` 方法中通過 `super().say_hello()` 調用了父類的方法。
丸趣 TV 網 – 提供最優質的資源集合!