“mro()”是什么意思?做?
示例来自 django.utils.function
< /a>:
for t in type(res).mro(): # <----- this
if t in self.__dispatch:
return self.__dispatch[t][funcname](res, *args, **kw)
What does mro()
do?
Example from django.utils.functional
:
for t in type(res).mro(): # <----- this
if t in self.__dispatch:
return self.__dispatch[t][funcname](res, *args, **kw)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
继续...:
只要我们有单一继承,
__mro__
只是以下元组:类、其基类、其基类的基类,依此类推,直至object
(当然仅适用于新式课程)。现在,通过多重继承...:
...您还可以保证,在
__mro__
中,没有类是重复的,并且没有类出现在其祖先之后,保存首先进入同一多重继承级别的类(如本例中的 B 和 C)位于从左到右的__mro__
中。从概念上讲,您在类实例上获得的每个属性(而不仅仅是方法)都会沿着 __mro__ 进行查找,因此,如果祖先中不止一个类定义了该名称,这会告诉您该属性将在哪里找到 - 在定义该名称的 __mro__ 的第一个类中。
Follow along...:
As long as we have single inheritance,
__mro__
is just the tuple of: the class, its base, its base's base, and so on up toobject
(only works for new-style classes of course).Now, with multiple inheritance...:
...you also get the assurance that, in
__mro__
, no class is duplicated, and no class comes after its ancestors, save that classes that first enter at the same level of multiple inheritance (like B and C in this example) are in the__mro__
left to right.Every attribute you get on a class's instance, not just methods, is conceptually looked up along the
__mro__
, so, if more than one class among the ancestors defines that name, this tells you where the attribute will be found -- in the first class in the__mro__
that defines that name.mro()
代表 方法解析订单。它返回类派生自的类型列表,按照搜索方法的顺序排列。mro()
和__mro__
仅适用于新样式类。在 Python 3 中,它们可以正常工作。然而,在 Python 2 中,这些类需要从object
继承。mro()
stands for Method Resolution Order. It returns a list of types the class is derived from, in the order they are searched for methods.mro()
and__mro__
work only on new style classes. In Python 3, they work without any issues. In Python 2, however, those classes need to inherit fromobject
.这也许会显示解析的顺序。
输出将是:
规则是深度优先,在本例中意味着
D
、B
、A
、C< /代码>。
Python 在搜索继承类时通常使用深度优先顺序,但是当两个类继承自同一个类时,Python 会从 MRO 中删除第一次提及该类。
This would perhaps show the order of resolution.
The output would be:
The rule is depth-first, which in this case would mean
D
,B
,A
,C
.Python normally uses a depth-first order when searching inheriting classes, but when two classes inherit from the same class, Python removes the first mention of that class from the MRO.
钻石继承中的解析顺序会有所不同。
Order of resolution will be different in diamond inheritance.
对于 @stryker 的示例,C3 算法为:
请参阅 Python 2.3 方法决议顺序 | Python.org
For @stryker 's example, the C3 algorithm is:
See The Python 2.3 Method Resolution Order | Python.org