Python 不自動調用父類 __init__ (C++/Java 自動)。子類覆寫 __init__ 後,必須顯式呼叫 父類初始化。
class A:
def method(self, arg):
pass
class B(A):
def method(self, arg):
# 1. 直接指定類名 (不推薦:硬編碼、多重繼承易出錯)
A.method(self, arg)
# 2. super(類型, 實例) - Python 2 風格,相容舊版
super(B, self).method(arg)
# 3. super() - Python 3 推薦,零參數自動推導
super().method(arg)
ob = B()
super(B, ob).method(arg) # 外部代碼調用 B 實例的父類方法
__init__ 鏈式調用最佳實踐
class A:
def __init__(self, x):
self.x = x
print("A init", x)
class B(A):
def __init__(self, x, y):
super().__init__(x) # 必須先調用父類 __init__
self.y = y
print("B init", y)
class C(B):
def __init__(self, x, y, z):
super().__init__(x, y) # 鏈式向上
self.z = z
print("C init", z)
c = C(1, 2, 3)
# 輸出:
# A init 1
# B init 2
# C init 3
class Base: pass
class Mixin1: pass
class Mixin2: pass
class Child(Mixin1, Mixin2, Base): pass
print(Child.__mro__)
# (, , , , )
super() 始終遵循 MRO 順序尋找下一個類super() 確保每個基類 __init__ 僅執行一次| 錯誤寫法 | 問題 | 正確寫法 |
|---|---|---|
super(B, self).__init__() 在 Python 3 | 雖可運行但冗餘 | super().__init__() |
忘記呼叫 super().__init__() | 父類未初始化,屬性缺失 | 首行呼叫 |
A.__init__(self) 硬編碼 | 多重繼承破壞 MRO | super().__init__() |
| 參數傳遞錯誤 | 父類簽名不符 | 檢查父類定義,正確轉遞 |
class B(A):
def __init__(self, x):
super(B, self).__init__(x) # 必須顯式傳類與實例
Python 3 僅建議使用無參數 super()。