具有多重继承的Python中的调用解析顺序

时间:2016-07-18 13:33:30

标签: python multiple-inheritance

我正在Youtube观看Python演讲,并发现了一个有趣的语言功能。但是,当我尝试运行测试代码时,它不起作用,我想了解原因。

我期待这个打印出来:

Parent
OtherParent

但我得到了这个:

Parent
Parent

示例代码:

class Parent:
    def get_message(self):
        return "Parent"

class Child(Parent):
    def do_print(self):
        print(super().get_message())

class OtherParent:
    def get_message(self):
        return "OtherParent"

class OtherChild(Child, OtherParent):
    pass

Child().do_print()
OtherChild().do_print()

编辑:在Windows上运行,Python 3.5.1,Anaconda 4.0.0(64位)

2 个答案:

答案 0 :(得分:1)

问题的评论中提到了正确的解释,即来自OtherChild类的MRO(评论中发布的链接:How does the order of mixins affect the derived class?)。

根据不同的遗传情况,查看OtherParent类MRO的不同输出:

  1. class OtherParent(): def get_message(self): return "OtherParent" print(OtherChild.__mro__) Child().do_print() OtherChild().do_print() 没有父类:

    Parent

    输出显示OtherParent来自(<class '__main__.OtherChild'>, <class '__main__.Child'>, <class '__main__.Parent'>, <class '__main__.OtherParent'>, <class 'object'>) Parent Parent

    Parent
  2. OtherParentclass OtherParent(Parent): def get_message(self): return "OtherParent" 的父类:

    OtherParent

    输出显示Parent之前出现(<class '__main__.OtherChild'>, <class '__main__.Child'>, <class '__main__.OtherParent'>, <class '__main__.Parent'>, <class 'object'>) Parent OtherParent

    OtherParent
  3. 案例2但是现在OtherChild首先从Child继承,然后是class OtherParent(Parent): def get_message(self): return "OtherParent" class OtherChild(OtherParent, Child): pass

    OtherParent

    输出显示ParentChild之前,但在(<class '__main__.OtherChild'>, <class '__main__.OtherParent'>, <class '__main__.Child'>, <class '__main__.Parent'>, <class 'object'>) Parent Parent 之前再次出现:

    assg_real_timestamp
  4. 也许有人可以解释最后一个看起来不自然的案例。

答案 1 :(得分:-2)

啊,我的朋友指出,与Youtube上的例子略有偏差:

class Parent:
    def get_message(self):
        return "Parent"

class Child(Parent):
    def do_print(self):
        print(super().get_message())

class OtherParent(Parent): # <----- Inheritance of Parent makes it work
    def get_message(self):
        return "OtherParent"

class OtherChild(Child, OtherParent):
    pass

Child().do_print()
OtherChild().do_print()