Why is this an ambiguous MRO?

▼魔方 西西 提交于 2019-12-17 16:56:10

问题


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"

Source

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

  1. Search in First if method does not exist in Third
  2. Search in Second if method does not exist in First

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

回答1:


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

  1. If a class inherits from multiple superclasses, the ones it lists earlier in the superclass list should come earlier in the MRO than the ones it lists later.
  2. Every class in the MRO should come before any of its superclasses.

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.

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



来源:https://stackoverflow.com/questions/47808926/why-is-this-an-ambiguous-mro

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!