Zihao

Make small but daily progress

0%

C3-Linearization--线性化python

为什么采用C3算法

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

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

线性化关系为:

1
2
3
4
5
6
7
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 代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#! /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__

输出结果为:

1
2
3
4
5
6
7
8
9
10
11
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

欢迎关注我的其它发布渠道