0

根据方法解析顺序

经典类使用简单的 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??
4

1 回答 1

2

元类仅适用于新型类,并通过__metaclass__在类主体中命名的字段来添加。拥有一个__metaclass__字段会导致该类成为一个新样式的类,无论您是否继承自object

class J:
  pass
class K(object):
  pass
class L:
  __metaclass__ = type

type(J) # <type 'classobj'>
type(K) # <type 'type'>
type(L) # <type 'type'>

因此,在您的示例中发生的情况似乎是由于词法/静态范围规则,当类主体第二次执行时,您的元类命名__metaclass__在范围内。D由于 Python__metaclass__在执行主体时会看到 a 在范围内,因此它将其用作元类D并将其转换为新样式的类,这会更改方法解析顺序。


您可能不应该命名 metaclass __metaclass__。将其命名为类似描述性的名称,PrettyPrintClassRepr并在需要时通过__metaclass__ = PrettyPrintClassRepr在类主体中使用将其应用于类:

class D:
  __metaclass__ = PrettyPrintClassRepr
于 2017-10-02T15:08:53.970 回答