根据方法解析顺序:
经典类使用简单的 MRO 方案:查找方法时,使用简单的深度优先从左到右方案搜索基类。
这可以在 Python 2.6 中验证
In [1]: import sys
In [2]: sys.version
Out[2]: '2.6.6 (r266:84292, Jul 23 2015, 15:22:56) \n[GCC 4.4.7 20120313 (Red Hat 4.4.7-11)]'
In [3]:
class D:
def f(self): return 'D'
class B(D): pass
class C(D):
def f(self): return 'C'
class A(B, C): pass
...:
In [4]: A().f()
Out[4]: 'D'
但是,如果我定义了一个元类,我会在 Python 2.7.12 中得到不同的结果:
Python 2.7.12 (default, Nov 19 2016, 06:48:10)
Type "copyright", "credits" or "license" for more information.
IPython 5.4.0 -- An enhanced Interactive Python.
? -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help -> Python's own help system.
object? -> Details about 'object', use 'object??' for extra details.
In [1]: class D: # Note: Old-style
...: def f(self): return "D.f()"
...: class B(D): pass
...: class C(D):
...: def f(self): return "C.f()"
...: class A(B, C): pass
...:
In [2]: A().f()
Out[2]: 'D.f()' # It works as expected.
In [3]: class __metaclass__(type):
...: "All classes are metamagically modified to be nicely printed"
...: __repr__ = lambda cls: cls.__name__
...:
In [4]: class D: # Note: Old-style
...: def f(self): return "D.f()"
...: class B(D): pass
...: class C(D):
...: def f(self): return "C.f()"
...: class A(B, C): pass
...:
In [5]: A().f()
Out[5]: 'C.f()' # WTF??