共計 643 個字符,預計需要花費 2 分鐘才能閱讀完成。
在 Python 中,可以使用構造函數實現子類調用父類的方法。以下是一個示例:
class ParentClass:
def __init__(self, x):
self.x = x
def print_x(self):
print('X:', self.x)
class ChildClass(ParentClass):
def __init__(self, x, y):
super().__init__(x) # 調用父類的構造函數
self.y = y
def print_y(self):
print('Y:', self.y)
child = ChildClass(10, 20)
child.print_x() # 調用父類方法
child.print_y() # 調用子類方法
在上面的例子中,ParentClass
是一個父類,它有一個構造函數 __init__()
和一個打印 x
值的方法 print_x()
。ChildClass
是一個繼承自 ParentClass
的子類,它也有一個構造函數 __init__()
和一個打印 y
值的方法print_y()
。
在 ChildClass
的構造函數中,我們使用 super().__init__(x)
來調用父類 ParentClass
的構造函數,并將參數 x
傳遞給父類的構造函數。這樣,子類可以繼承父類的屬性和方法。
最后,我們創建一個 ChildClass
的實例 child
,并調用print_x()
和print_y()
方法,分別打印父類的 x
值和子類的 y
值。
丸趣 TV 網 – 提供最優質的資源集合!
正文完