为什么这是模棱两可的MRO? [英] Why is this an ambiguous MRO?

查看:111
本文介绍了为什么这是模棱两可的MRO?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class First(object):
    def __init__(self):
        print "first"

class Second(First):
    def __init__(self):
        print "second"

class Third(First, Second):
    def __init__(self):
        print "third"

来源

为什么Python无法创建一致的MRO?在我看来,这很清楚:

Why can't Python create a consistent MRO? It seems to me it's pretty clear:

  1. 如果方法在第三"中不存在,则在第一"中搜索
  2. 如果First中不存在方法,则在Second中搜索

但是,如果您尝试一下:

But if you try it out:

TypeError: Error when calling the metaclass bases
    Cannot create a consistent method resolution
order (MRO) for bases First, Second

推荐答案

要保持一致",MRO应该满足以下约束条件:

To be "consistent" the MRO should satisfy these constraints:

  1. 如果一个类继承自多个超类,则它在超类列表中较早列出的那些在MRO中应该比在其后列出的那些更早出现.
  2. MRO中的每个类都应排在其任何超类之前.

您提出的层次结构没有满足这些限制的任何可能的排序.因为将Third定义为在First之前继承First,所以MRO中First应该在Second之前.但是由于第二继承自第一,因此第二应该在MRO中先于第一.这种矛盾无法调和.

Your proposed hierarchy does not have any possible ordering meeting these constraints. Because Third is defined to inherit from First before Second, First should come before Second in the MRO. But because Second inherits from First, Second should come before First in the MRO. This contradiction cannot be reconciled.

您可以阅读有关Python用于计算MRO的精确方法的更多信息,该方法称为 C3线性化算法.

You can read more about the precise method Python uses to compute the MRO, which is called the C3 linearization algorithm.

这篇关于为什么这是模棱两可的MRO?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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