Python多重继承超级功能 [英] Python multiple inheritance super function

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

问题描述

我对python多重继承有点困惑.

I am little confused about python multiple inheritance.

例如,如果您拥有:

class A(object):
def __init__(self):
    print "init A"
    super(A, self).__init__()

class B(A):
    def __init__(self):
        print "init B"
        super(B, self).__init__()

class C(A):
    def __init__(self):
        print "init C"
        super(C, self).__init__()

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

if __name__ == '__main__':
    D()

方法解析顺序(MRO)为D-C-B-A.

The method resolution order (MRO) would be D-C-B-A.

为什么订单不是D-C-A-B-A?

Why the order is not D-C-A-B-A?

推荐答案

Python文档:

对于新型类,动态排序是必需的,因为所有多重继承的情况都具有一个或多个菱形关系(其中至少一个父类可以通过从最底层类访问的多个路径进行访问).例如,所有新样式类都从对象继承,因此任何多重继承的情况都提供了不止一个到达对象的路径. 为防止基类被多次访问,动态算法采用一种线性化搜索顺序的方式,即保留每个类中指定的从左到右的顺序,即只调用每个父级一次,并且这是单调的(意味着可以在不影响其父级的优先顺序的情况下将一个类进行子类化).综合考虑这些属性,可以设计具有多重继承的可靠且可扩展的类.有关更多详细信息,请参见 https://www.python.org/download/releases/2.3 /mro/.

With new-style classes, dynamic ordering is necessary because all cases of multiple inheritance exhibit one or more diamond relationships (where at least one of the parent classes can be accessed through multiple paths from the bottommost class). For example, all new-style classes inherit from object, so any case of multiple inheritance provides more than one path to reach object. To keep the base classes from being accessed more than once, the dynamic algorithm linearizes the search order in a way that preserves the left-to-right ordering specified in each class, that calls each parent only once, and that is monotonic (meaning that a class can be subclassed without affecting the precedence order of its parents). Taken together, these properties make it possible to design reliable and extensible classes with multiple inheritance. For more detail, see https://www.python.org/download/releases/2.3/mro/.

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

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