共計 501 個字符,預計需要花費 2 分鐘才能閱讀完成。
在 Python 中,可以使用 super() 函數來調用父類的構造函數。通過 super() 函數,可以獲得父類的對象,并調用父類的方法。在子類的構造函數中,可以使用 super().__init__() 來調用父類的構造函數。示例代碼如下:
class ParentClass:
def __init__(self, arg1, arg2):
self.arg1 = arg1
self.arg2 = arg2
class ChildClass(ParentClass):
def __init__(self, arg1, arg2, arg3):
super().__init__(arg1, arg2)
self.arg3 = arg3
child = ChildClass(arg1_value, arg2_value, arg3_value)
在上述示例中,ChildClass繼承自 ParentClass。在ChildClass 的構造函數中,通過 super().__init__(arg1, arg2) 調用了 ParentClass 的構造函數,并傳入所需的參數。這樣可以保證在創建 ChildClass 對象時,父類的構造函數也會被調用。
丸趣 TV 網 – 提供最優質的資源集合!
正文完