Python之从继承到C3算法

在Python2.X和Python3.X有很多不同的地方,其中一个区别就是和继承有关。

在Python3.X中,一个类如果没有指明其继承哪个类的时候,其默认就是继承object类。

而在Python2.X就没有这个默认这个选项。

和继承有关的另外一个区别就是在多继承的时候,Python2.X在多继承中,使用的深度优先搜索规则,而Python3.X使用的并不是大家所以为的广度优先算法,而是C3算法,只是在大多数情况下,C3算法的结果恰巧符合广度优先算法的结果。

此处应有示例。

关于C3算法, 在Python官方文档中是这样解释的:

  take the head of the first list, i.e L[B1][0]; if this head is not in the tail of any of the other lists, then add it to the linearization of C and remove it from the lists in the merge, otherwise look at the head of the next list and take it, if it is a good head. Then repeat the operation until all the class are removed or it is impossible to find good heads. In this case, it is impossible to construct the merge, Python 2.3 will refuse to create the class C and will raise an exception.

C3算法的本质就是Merge, 不断地把mro()函数返回的队列进行Merge,规则如下:

  (1)如果第一个序列的第一个元素,是后续序列的第一个元素,或者在后续序列中没有再次出现,则将这个元素合并到最终的方法解析顺序序列中, 并从当前操作的全部序列中删除。

  (2)如果不符合,则跳过此元素,查找下一个列表的第一个元素,重复1的判断规则。

例如,有段代码的如下:

此处应有代码

那么它的C3算法的推测步骤就是

mro(A) = [AO]
mro(B) = [B] + merge(mro(A))
= [B] + merge([AO])
= [BA] + merge([O])
= [BAO]
mro(C) = [C] + merge(mro(A))
= [CAO]
mro(D) = [D] + merge(mro(B)+mro(C) + [BC])
= [D] + merge([BAO],[CAO],[BC])
= [DB] + merge([AO],[CAO],[C])
= [DBC] + merge([AO],[AO])
= [DBCA] + merge([O],[O])
= [DBCAO]
posted @ 2018-08-16 09:31  _杨魏  阅读(447)  评论(0编辑  收藏  举报