关于 python class 的超继承和多重继承

About super and mult-inherit of python class

我用的是Python3.6.3

我有以下代码:

class Parent:
    def __init__(self, **kw):
        print("init parent")

class PP:
    def __init__(self, **kw):
        print("init PP")


class Child(PP, Parent):
    def __init__(self, **kw):
        print("init child")
        super().__init__()

exp=Child()

我预计:

init child
init PP
init parent

但我得到了:

init child
init PP

当我尝试打印MRO时,我得到了正确答案

print(exp.__class__.mro())

[<class '__main__.Child'>, <class '__main__.PP'>, <class '__main__.Parent'>, <class 'object'>]

为什么没有打印 parent

Python 不会自动调用 Parent__init__。您必须在 PP:

中使用 super().__init__() 明确地执行此操作
class Parent:
    def __init__(self, **kw):
        print("init parent")

class PP:
    def __init__(self, **kw):
        print("init PP")
        super().__init__()


class Child(PP, Parent):
    def __init__(self, **kw):
        print("init child")
        super().__init__()

exp = Child()

现在输出是:

init child
init PP
init parent