萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

深入理解 Python super() 的運作機制與多重繼承優勢

super() 是 Python 解決多重繼承鑽石問題的關鍵機制。單繼承下直接呼叫父類方法與 super() 效果相同,但多重繼承時 super() 能依據方法解析順序(MRO)確保共同父類只被初始化一次,避免重複調用。

傳統繼承 vs super() 繼承

傳統寫法

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)

super() 寫法

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 所有類別)。
  • 經典類(Python 2 不繼承 object)使用 super() 會拋出 TypeError: super() argument 1 must be type, not classobj。
  • 專案中應保持一致:要么全用 super(),要么全用顯式父類名,切勿混用。
copyright © 萬盛學電腦網 all rights reserved