区块链

C3 Linearization 线性化python

2018-03-31  本文已影响13人  金牛茶馆

为什么采用C3算法

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

线性化关系为:

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

上一篇下一篇

猜你喜欢

热点阅读