Python之MRO及其C3算法

时间:2022-11-16 16:42:31
[<class '__main__.B'>, <class '__main__.A'>, <class 'object'>]
(<class '__main__.B'>, <class '__main__.A'>, <class 'object'>)
(<class '__main__.B'>, <class '__main__.A'>, <class 'object'>)

推荐+收藏:两篇不错的文章:

你真的理解Python中MRO算法吗?

python MRO:C3算法

MRO:Method Resolution Order 方法解析顺序,Python支持多继承,该方法用于解决父类存在同名函数的时存在的二义性问题。

单调性:某一个类继承的父类满足从左到右的顺序解析(从左到右递归地从左到右解析)

获取解析顺序的几种方法:

import inspect
class A:
pass
class B(A):
pass print(B.mro())
print(B.__mro__)
print(inspect.getmro(B))

输出结果:

[<class '__main__.B'>, <class '__main__.A'>, <class 'object'>]
(<class '__main__.B'>, <class '__main__.A'>, <class 'object'>)
(<class '__main__.B'>, <class '__main__.A'>, <class 'object'>)