在Python中具有多重继承的MRO [英] MRO with multiple inheritance in python

查看:118
本文介绍了在Python中具有多重继承的MRO的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python网页上的文档中 python中经典类的顺序被描述为深度优先的从左到右搜索.我试图用这段代码对此进行测试:

In the documentation on the Python webpage the method resolution order for classic classes in python is described as a depth-first left-to-right search. I tried to test this with this piece of code:

class A(object):
def __init__(self):
    print "Initialized A"

class B(A):
    def test():
        print "Initialized B"

class C(A):
    def __init__(self):
        print "Initialized C"

class D(B, C):
    def __init__(self):
        super(D, self).__init__()
        print "Initialized D"

当我创建对象D的实例时:

When I create an instance of object D:

D()

我得到结果:

Initialized C
Initialized D

虽然我期望打印"Initialized A","Initialized D",因为MRO是深度优先的,所以首先在B中搜索初始化,当未找到(是这种情况)时,它应该在层次结构中更深在B的基类(即A)中查找函数.有人可以给我一个解释,为什么我得到C的初始化函数而不是A的初始化函数?

While I expected the prints "Initialized A", "Initialized D" since the MRO is depth-first, the initialization is first searched in B, when not found (which is the case) it should go deeper in the hierarchy and look for the function in the base class of B (i.e. A). Can someone give me an explanation why I get the init-function of C instead of that one of A?

推荐答案

您的类继承自object,因此不是经典类.这是一种新型的类. (任何从新样式类继承的类也是新样式类.)

Your class inherits from object and is thus not a classic class. It is a new-style class. (Any class that inherits from a new-style class is also a new-style class.)

请注意,super仍然不能与经典类一起使用.当您尝试访问未在实例上直接定义的属性时,您引用的深度从左到右"规则只是针对订单基类的属性查找规则.经典类不提供这样的MRO ---在没有显式引用特定超类的情况下,无法访问属性的超类值".

Note that super can't be used with classic classes anyway. The "depth first left to right" rule you cite is just the attribute lookup rule for the order base classes are searched when you try to access an attribute that is not directly defined on the instance. Classic classes don't provide an MRO as such --- there isn't any way to access "the superclass value" of an attribute without explicitly referencing a particular superclass.

这篇关于在Python中具有多重继承的MRO的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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