首页 > 解决方案 > 为什么Python中类继承中的一些__init__方法没有被调用?

问题描述

正如我在标题中提到的,我想知道为什么__init__不调用某些方法。这是我的例子:

class Type(type):
    def __repr__(cls):
        return cls.__name__

class A(object, metaclass=Type):
    def __init__(self):
        print("A")

class B(A):
    def __init__(self):
        print("B1")
        super().__init__()
        print("B2")

class D(object, metaclass=Type):
    def __init__(self):
        print("D")

class E(B):
    def __init__(self):
        print("E1")
        super().__init__()
        print("E2")

class F(D, E):
    def __init__(self):
        print("F1")
        super().__init__()
        print("F2")

print(F.mro())
F()

它返回方法应该被继承的顺序 ( mro()) 和实际结果:

[F, D, E, B, A, <class 'object'>]
F1
D
F2

为什么实际结果与以下不同:

F1
D1
E1
B1
A
B2
E2
D2
F2

正如 MRO 所建议的那样?

我知道一半的答案,即缺少__init__inA的类定义打破了这个链条,但为什么呢?

标签: pythonmethod-resolution-order

解决方案


推荐阅读