當子類中實現了 __init__ 方法,
基類的初始化方法並不會被調用 def __init__(self, ...)
In [169]: # 此示例示意 用super函數顯示調用基類__init__初始化方法
...: class Human: ...: def __init__(self, n, a): ...: self.name, self.age = n, a ...: print("Human的__init__方法被調用") ...: ...: def infos(self): ...: print("姓名:", self.name) ...: print("年齡:", self.age) ...: ...: ...: class Student(Human): ...: def __init__(self, n, a, s=0): ...: super().__init__(n, a) # 顯式調用父類的初始化方法
...: self.score = s # 添加成績屬性
...: print("Student類的__init__方法被調用") ...: ...: def infos(self): ...: super().infos() # 調用父類的方法
...: print("成績:", self.score) ...: ...: ...: s1 = Student('小張', 20, 100) ...: s1.infos() Human的__init__方法被調用 Student類的__init__方法被調用 姓名: 小張 年齡: 20 成績: 100