1. 程式人生 > >關於Python3 類多繼承初始化的一些問題

關於Python3 類多繼承初始化的一些問題

Python3分析類的繼承結構時採用廣度優先演算法, 所以出現如下鑽石繼承情況時:



class Base:
    def __init__(self):
        print("THIS IS BASE.")


class Base1(Base):
    def __init__(self):
        print("This is Base1.")
        super().__init__()


class Base2(Base):
    def __init__(self):
        print("This is Base2." )
        super().__init__()


class Child(Base2, Base1):
    def __init__(self):
        print("This is Child.")
        super().__init__()



Child()

輸出結果如下:

This is Child.
This is Base2.
This is Base1.
THIS IS BASE.

執行順序大致是 Child -> Base2 -> Base1 -> Base.

證明:

class Base:
    def __init__(self):
        print("THIS IS BASE.")


class Base1(Base):
    def __init__(self, t):
        print("This is Base1.%d" %t)
        super().__init__()


class Base2(Base):
    def __init__(self, t):
        print("This is Base2.%d" %t)
        super().__init__(t - 1)


class Child(Base2, Base1):
    def __init__(self, t):
        print("This is Child.%d" %t)
        super().__init__(t - 1)
        self.z = t


Child(3)

輸出:

This is Child.3
This is Base2.2
This is Base1.1
THIS IS BASE.