“mro()"是什么?做? [英] What does "mro()" do?

查看:56
本文介绍了“mro()"是什么?做?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

django.utils.functional.py中:

for t in type(res).mro(): # <----- this如果 t 在 self.__dispatch:返回 self.__dispatch[t][funcname](res, *args, **kw)

我不明白mro().它有什么作用?mro"是什么意思?

解决方案

关注...:

<预><代码>>>>A类(对象):通过...>>>A.__mro__(<class '__main__.A'>, <type 'object'>)>>>B(A)类:通过...>>>B.__mro__(<class '__main__.B'>, <class '__main__.A'>, <type 'object'>)>>>C(A)类:通过...>>>C.__mro__(<class '__main__.C'>, <class '__main__.A'>, <type 'object'>)>>>

只要我们有单继承,__mro__ 只是以下的元组:类、它的基、它的基的基等等直到 object(仅当然适用于新型课程).

现在,有了多重继承...:

<预><代码>>>>D(B,C)类:通过...>>>D.__mro__(<class '__main__.D'>, <class '__main__.B'>, <class '__main__.C'>, <class '__main__.A'>, <type 'object'>)

...您还可以保证,在 __mro__ 中,没有类是重复的,也没有类在其祖先之后,除了首先进入同一级多重继承的类(像这个例子中的 B 和 C)在 __mro__ 从左到右.

您在类的实例上获得的每个属性,而不仅仅是方法,在概念上都是沿着 __mro__ 查找的,因此,如果祖先中有多个类定义了该名称,这会告诉您在哪里将在定义该名称的 __mro__ 中的第一个类中找到属性.

In django.utils.functional.py:

for t in type(res).mro():  # <----- this
    if t in self.__dispatch:
        return self.__dispatch[t][funcname](res, *args, **kw)

I don't understand mro(). What does it do and what does "mro" mean?

解决方案

Follow along...:

>>> class A(object): pass
... 
>>> A.__mro__
(<class '__main__.A'>, <type 'object'>)
>>> class B(A): pass
... 
>>> B.__mro__
(<class '__main__.B'>, <class '__main__.A'>, <type 'object'>)
>>> class C(A): pass
... 
>>> C.__mro__
(<class '__main__.C'>, <class '__main__.A'>, <type 'object'>)
>>> 

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 to object (only works for new-style classes of course).

Now, with multiple inheritance...:

>>> class D(B, C): pass
... 
>>> D.__mro__
(<class '__main__.D'>, <class '__main__.B'>, <class '__main__.C'>, <class '__main__.A'>, <type 'object'>)

...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()"是什么?做?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆