super() 是 Python 解決多重繼承鑽石問題的關鍵機制。單繼承下直接呼叫父類方法與 super() 效果相同,但多重繼承時 super() 能依據方法解析順序(MRO)確保共同父類只被初始化一次,避免重複調用。
class FooParent:
def __init__(self):
self.parent = "I'm the parent."
print('Parent')
def bar(self, msg):
print(msg, 'from Parent')
class FooChild(FooParent):
def __init__(self):
FooParent.__init__(self) # 硬編碼父類名
print('Child')
def bar(self, msg):
FooParent.bar(self, msg)
print('Child bar function')
print(self.parent)
class FooParent:
def __init__(self):
self.parent = "I'm the parent."
print('Parent')
def bar(self, msg):
print(msg, 'from Parent')
class FooChild(FooParent):
def __init__(self):
super().__init__() # Python 3 簡潔寫法
print('Child')
def bar(self, msg):
super().bar(msg)
print('Child bar function')
print(self.parent)
兩者輸出相同:
Parent
Child
HelloWorld from Parent
Child bar function
I'm the parent.
class Base:
def __init__(self):
print('Base init')
class A(Base):
def __init__(self):
super().__init__()
print('A init')
class B(Base):
def __init__(self):
super().__init__()
print('B init')
class C(A, B):
def __init__(self):
super().__init__()
print('C init')
c = C()
# 輸出順序遵循 MRO: C -> A -> B -> Base
# Base init 僅執行一次
super() 僅適用於新式類(繼承自 object 或 Python 3 所有類別)。super() 會拋出 TypeError: super() argument 1 must be type, not classobj。super(),要么全用顯式父類名,切勿混用。