Python中多重继承时方法解析顺序MRO(C3算法的应用)

2019-11-05  本文已影响0人  0bug

在计算机科学中,C3算法主要用于确定多重继承时,子类应该继承哪一个父类的方法,即方法解析顺序(Method Resolution Order,MRO)。

C3算法实现了三种重要特性:

1996年的OOPSLA会议上,论文"A Monotonic Superclass Linearization for Dylan首次提出了C3超类线性化。被Python2.3选作方法解析的默认算法。

其他查找算法与C3算法的 比较:

深度优先 广度优先 C3

Python提供了__mor__mor() 来查看类的方法解析顺序

以下的例子需在Python2.3及以后的版本上执行(本例使用Python3.5)

例子1:

class D(object):
    pass


class C(D):
    pass


class B(D):
    pass


class A(B, C):
    pass


print(A.__mro__)

# (<class '__main__.A'>, <class '__main__.B'>, <class '__main__.C'>, 
<class '__main__.D'>, <class 'object'>)

例子2:

class D(object):
    pass


class C(D):
    pass


class B(D):
    pass


class A(B, C):
    pass


print(A.mro())

# [<class '__main__.A'>, <class '__main__.B'>, <class '__main__.C'>, 
<class '__main__.D'>, <class 'object'>]

例子3:

class D(object):
    pass


class E(object):
    pass


class C(E):
    pass


class B(D):
    pass


class A(B, C):
    pass


print(A.__mro__)

# (<class '__main__.A'>, <class '__main__.B'>, <class '__main__.D'>, 
<class '__main__.C'>, <class '__main__.E'>, <class 'object'>)

例子4

class B(object):
    pass


class C(B):
    pass


class A(C, B):
    pass


print(A.__mro__)

例子5

class B(object):
    pass


class C(B):
    pass


class A(B,C):
    pass


print(A.__mro__)

""" 
说明:
这样写会报错:
TypeError: Cannot create a consistent method resolution
order (MRO) for bases B, C
"""
上一篇下一篇

猜你喜欢

热点阅读