如何在python2中了解MRO

时间:2017-08-30 14:06:29

标签: python-2.x method-resolution-order

在python3中,我们可以使用'__mro__'来获取方法解析顺序,如下所示:

>>> class a:
...     pass
...  
>>> a.__mro__
(<class '__main__.a'>, <class 'object'>)
>>> 

python2有替代方法吗?我试图找到一个但失败了。

>>> class a:
...     pass
... 
>>> dir(a)
['__doc__', '__module__']
>>> class a(object):
...     pass
... 
>>> dir(a)
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__']

1 个答案:

答案 0 :(得分:2)

自Python 2.2(https://www.python.org/download/releases/2.3/mro/

以来,

mro()可用

但是,该类必须是新的样式类。

>>> class A: pass
>>> A.mro()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: class A has no attribute 'mro'

>>> class A(object): pass
>>> A.mro()
[<class '__main__.A'>, <type 'object'>]