Python継承特性

2185 ワード

Pythonは多重継承をサポートし、多重継承はダイヤモンド型継承シーンの下のベースクラス呼び出し順序と方法の再ロード解析という問題が発生し、多重継承はインタフェース実装メカニズムを解決することができる.この方法について詳しく説明します.
Pythonはマルチ継承をサポートする動的言語であり,チェーンの解析順序を継承する際にマルチ継承によって形成された図を線形化し,最後にその線形化の順序によって呼び出すメソッド名を決定する.
Python言語継承に関するアルゴリズムは以下の通りである.
L(C(X 1,...,Xn):クラスCの継承シーケンス
L(C(X1,…,Xn)) = C ∪ Merge(L(X1),L(X2),…,L(Xn),X1,…,Xn)
Merge関数は次のように定義されます.
Merge(L(X 1),L(X 2),…,L(Xn),X 1,…,Xn):一つのXiを選択して以下の条件を満たす:
iは、チェーン内のヘッダ要素を継承し、他のL(Xi)の末尾に現れない必要がある.
条件1が満たされた場合、Xiを出力し、その要素を削除して条件1を実行し続ける.例外を投げ出す
異なるのはクラスA,Bの継承順序が異なり,実装コードは以下の通りである.
class X(object):
    def show(self):
        print("X::show()")

class Y(object):
    def show(self):
        print("Y::show()")

class A(X,Y):
    def show(self):
        print("A::show()")

class B(Y,X):
    def show(self):
        print("B::show()")

class C(A,B):
    pass


if __name__ == "__main__":
    c = C()
    c.show()
print(c.__mro__)

計算継承チェーンは次のとおりです.

L(X) = {object}
L(Y) = {object}
L(A(X,Y)) = A ∪ Merge(L(X),L(Y),X,Y)
  = {A} ∪ Merge(X,Y,{object},{object}})
  = {A,X,Y,object}
L(B(Y,X)) = B ∪ Merge(L(Y),L(X),Y,X)
   = {B} ∪ Merge(Y,X,{object},{ object})
   = {B,Y,X,object}
L(C(A,B)) = C ∪ Merge(L(A),L(B),A,B)
   = {C} ∪ Merge({A,X,Y,object},{B,Y,X,object},A,B)
   = {C,A,B} ∪ Merge({X,Y,object},{Y,X,object})

多重継承の場合、コンストラクション関数の初期化時にsuper()方式で構築されます.クラス名呼び出しを使用すると、同じコンストラクション関数が複数回呼び出され、呼び出し順序は表示呼び出し順序に依存します.
class X(object):
    def __init__(self):
        super().__init__()
        print("X::init")
        self.value = 1

class Y(object):
    def __init__(self):
        super().__init__()
        print("Y::init")
        self.value = 2


class A(X,Y):
def __init__(self):
  //     X.__init__(self)、Y.__init__(self)
        super().__init__()
        print("A::init")
        self.value = 3

class B(Y,X):
    def __init__(self):
        super().__init__()
        print("B::init")
        self.value = 4


class C(B):
    def __init__(self):
        super().__init__()
        print("C::init")
        self.value = 5