美文网首页区块链
C3 Linearization 线性化python

C3 Linearization 线性化python

作者: 金牛茶馆 | 来源:发表于2018-03-31 20:24 被阅读13次

    为什么采用C3算法

    C3算法最早被提出是用于Lisp的,应用在Python中是为了解决原来基于深度优先搜索算法不满足本地优先级,和单调性的问题。

    • 本地优先级:
      指声明时父类的顺序,比如C(A,B),如果访问C类对象属性时,该根据声明顺序,优先查找A类,然后再查找B类。
    • 单调性:
      如果在C的解析顺序中,A排在B的前面,那么在C的所有子类里,也必须满足这个顺序。

    线性化关系为:

    L(7) = {'object'}
    L(4) = {'4','7'}
    L(5) = {'5','7'}
    L(6) = {'6','7'}
    L(2) = {'2','4','5','7','object'}
    L(3) = {'3','4','6','7','object'}
    L(1) = {'1','2','3','4','5','6','7','object'}
    

    python 代码如下:

    #! /usr/bin/env python
    # 
    # multi inheritance view
    # /------ 7-------\ 
    # / | \
    # 4 - 5 6
    # \\ / /
    # 2-/\--- 3------/
    # \ / 
    # 0,1 
    #
    #
    
    class C7(object):
        def test(self):
            print 'test in C7'
    
    class C4(C7):
        def test(self):
            print 'test in C4'
    
    class C5(C7):
        def test(self):
            print 'test in C5'
    
    class C6(C7):
        def test(self):
            print 'test in C6'
    
    class C2(C4,C5):
        def test(self):
            print 'test in C2'
    
    class C3(C4,C6):
        pass
    
    class C1(C2,C3):
        pass
    
    class C0(C2,C3):
        def test(self):
            print 'test in C0'
            super(C3,self).test()
    
    if __name__ == "__main__":
        
        c1 = C1()
        c1.test()
        c0 = C0()
        c0.test()
        print C7.__mro__
        print C6.__mro__
        print C5.__mro__
        print C4.__mro__
        print C3.__mro__
        print C2.__mro__
        print C1.__mro__
        print C0.__mro__
    

    输出结果为:

    test in C2
    test in C0
    test in C4
    (<class '__main__.C7'>, <type 'object'>)
    (<class '__main__.C6'>, <class '__main__.C7'>, <type 'object'>)
    (<class '__main__.C5'>, <class '__main__.C7'>, <type 'object'>)
    (<class '__main__.C4'>, <class '__main__.C7'>, <type 'object'>)
    (<class '__main__.C3'>, <class '__main__.C4'>, <class '__main__.C6'>, <class '__main__.C7'>, <type 'object'>)
    (<class '__main__.C2'>, <class '__main__.C4'>, <class '__main__.C5'>, <class '__main__.C7'>, <type 'object'>)
    (<class '__main__.C1'>, <class '__main__.C2'>, <class '__main__.C3'>, <class '__main__.C4'>, <class '__main__.C5'>, <class '__main__.C6'>, <class '__main__.C7'>, <type 'object'>)
    (<class '__main__.C0'>, <class '__main__.C2'>, <class '__main__.C3'>, <class '__main__.C4'>, <class '__main__.C5'>, <class '__main__.C6'>, <class '__main__.C7'>, <type 'object'>)
    

    更多可以查看 wiki

    相关文章

      网友评论

        本文标题:C3 Linearization 线性化python

        本文链接:https://www.haomeiwen.com/subject/puqncftx.html