# Method Resolution Order

## 1. 定义

MRO 指明了在继承中，当类本身和基类中同时有多个同名函数定义的时候，应该如何查找最终智行的函数。本身是ordering of the inheritance graph.

2. 查看
YOUR_CLASS.__mro__ 或者是 YOUR_CLASS.mro()

<span style="font-family:Microsoft YaHei;">class A(object):
def func(self):
return 'A.func'

class B(A):
def func(self):
return 'B.func'

class C(A):
def func(self):
return 'C.func'

class D(C, B):
pass

print D.mro()</span>

<span style="font-family:Microsoft YaHei;">[<class '__main__.D'>, <class '__main__.C'>, <class '__main__.B'>, <class '__main__.A'>, <type 'object'>]</span>

3. 使用

<span style="font-family:Microsoft YaHei;"><span style="font-family:Microsoft YaHei;font-size:14px;">d = D()
d.func()</span></span>

<span style="font-family:Microsoft YaHei;">'C.func'</span>

## 4.计算

C3--python中计算MRO的算法，参考网址：The Python 2.3 Method Resolution Order  and  C3
C3 makes sure:
1) subclass在 base class之前
2) base class from class definition is preserved
3) First two qualities are preserved no matter where you stat in the inheritance graph.

L[C] 是C加上 父类线性值和父类list的merge结果，公式如下：
L[C (B1, B2, ...Bn)] = C +merge (L[B1], L[B2],.....  L[Bn],  B1,  B2, ....., Bn)

merge的核心描述是：
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.

<span style="font-family:Microsoft YaHei;">def _c3_merge(sequences):
"""Merges MROs in *sequences* to a single MRO using the C3 algorithm.
"""
result = []
while True:
sequences = [s for s in sequences if s]   # purge empty sequences
if not sequences:
return result
for s1 in sequences:   # find merge candidates among seq heads
candidate = s1[0]
for s2 in sequences:
if candidate in s2[1:]:
candidate = None
break      # reject the current head, it appears later
else:
break
if candidate is None:
raise RuntimeError("Inconsistent hierarchy")
result.append(candidate)
# remove the chosen candidate
for seq in sequences:
if seq[0] == candidate:
del seq[0]
</span>

# 5.应用

"The __mro__ attribute of the type lists the method resolution search order used by both getattr() and super()."

# Built-In Super Function

## 1. 定义

“Given a method resolution order and a class C,super() gives you a object which resolves methods using only the part of the MRO which comes after C”。
super() 其实是返回了一个proxy对象，该对象是用来路由method调用的。
def super(type, object_or_type):
pass

## 2. 参数说明：

### 1） instance-bound：

super(class, instance-of-class), 要求instance必须是class的实例（isinstance(instance, class)=true）。

• 拿到第二个参数的类型对应的MRO
• 找到第一个参数class在MRO中的位置
• 然后使用该class在MRO之后的所有class来用于解析method

### 2） class-bound：

super(base-class, derived-class), 要求derived-class 必须是base-class的子类(更准确的是issubclass(derived-class, base-class)=true)，否则抛异常。

• python 拿到 derived class的MRO
• 然后在MRO里面找到base class
• 然后从base class后面的所有class中找到最先匹配函数的那个类。

## 3. 没有参数的super()

1） 在instance method中，等同于 super(class-of-method, self)
2 )  在class method中， 等同于 super( class-of-method, class)

• 本文已收录于以下专栏：

## logiscope 应用度量元 翻译和解释

Metric Name Max Min 解释 Ratio of repeated inheritances in the application ...

## polymorphism&amp;inheritance feature example in C++

• 2011年01月09日 23:34
• 20KB
• 下载

## JavaScript OOP (Polymorphism and Inheritance)

Object Oriented Programming Goals I assume that the reader has a basic familiarity with JavaScript,...

## Java学习笔记（11）Inheritance and Polymorphism

11.1超类（Superclass）和子类（Subclasses） 对一个已有的类做扩充，叫做继承。被继承的那个已有类叫做超类（superclass），新的那个类叫子类（subclass）。 继承性是...

## 3ds Max角色绑定教程-Pushing Your Character Rigs Beyond the Basics in 3ds Max

• 2017年10月16日 07:25
• 687B
• 下载

## Mastering iOS frameworks Beyond the Basics 第二版

• 2017年07月21日 10:25
• 40.04MB
• 下载

## 有关Python的inheritance

• 2017年02月16日 21:35
• 3.38MB
• 下载

## Mastering iOS Frameworks Beyond the Basics(2nd) 无水印pdf

• 2017年10月16日 22:19
• 22.71MB
• 下载

## Protocol Buffers: (7) Protocol Buffer Basics: Python

Protocol Buffer Basics: Python This tutorial provides a basic Python programmer's introduction ...

举报原因： 您举报文章：Python-Beyond the Basics--Inheritance & Subtype Polymorphism 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)