Python的方法解析顺序(MRO)

mro即method resolution order,主要用于在多继承时判断调的属性的路径(来自于哪个类)。

http://blog.csdn.net/imzoer/article/details/8737642

 

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

 API:

 1 class type(object):
 2     """
 3     type(object) -> the object's type
 4     type(name, bases, dict) -> a new type
 5     """
 6     def mro(self): # real signature unknown; restored from __doc__
 7         """
 8         mro() -> list
 9         return a type's method resolution order
10         """
11         return []

 

测试代码:

 1 #!/usr/bin/env python
 2 class A(object):
 3     def __init__(self):
 4         print "enter A"
 5         print("leave A")
 6 
 7 
 8 class B(object):
 9     def __init__(self):
10         print "enter B"
11         print "leave B"
12 
13 
14 class C(A,B):
15     def __init__(self):
16         print "enter C"
17         super(C, self).__init__()
18         print "leave C"
19 
20 b = C()
21 mo = b.__class__.mro()
22 print mo

 

输出:

enter C
enter A
leave A
leave C
[<class '__main__.C'>, <class '__main__.A'>, <class '__main__.B'>, <type 'object'>]

posted @ 2016-11-13 22:07  PKICA  阅读(344)  评论(0编辑  收藏  举报