【问题标题】:Python - Peculiarities in method resolution orderPython - 方法解析顺序的特点
【发布时间】:2018-05-07 07:05:43
【问题描述】:

让我们拥有以下 Python2 代码:

#!/usr/bin/python

class A1(object):
    def __init__(self):
        super(A1, self).__init__()
        print "A1.__init__"

class A2(A1):
    def __init__(self):
        super(A2, self).__init__()
        print "A2.__init__"

class B1(object):
    def __init__(self):
        super(B1, self).__init__()
        print "B1.__init__"

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

class C(A2, B2):
    def __init__(self):
        super(C, self).__init__()
        print "C.__init__"

C()
print C.mro()

C继承自两个没有共同祖先的前驱类分支(除了默认的object,不确定这有多重要)。代码输出:

B1.__init__
B2.__init__
A1.__init__
A2.__init__
C.__init__
[<class '__main__.C'>, <class '__main__.A2'>, <class '__main__.A1'>, <class '__main__.B2'>, <class '__main__.B1'>, <type 'object'>]

完全符合预期。

现在说我粗心,忘记在A1B1 中调用super().__init__()(我不在乎初始化object 那么多......)。然后输出变为:

A1.__init__
A2.__init__
C.__init__
[<class '__main__.C'>, <class '__main__.A2'>, <class '__main__.A1'>, <class '__main__.B2'>, <class '__main__.B1'>, <type 'object'>]

现在只有A1-A2 分支被初始化——而C.mro() 根本没有改变!

这种行为的原因是什么?

【问题讨论】:

    标签: python multiple-inheritance init super method-resolution-order


    【解决方案1】:

    MRO 的打印输出准确地向您展示了这是为什么。 Python 以特定顺序调用父方法,因此得名。它调用A2的方法,它有一个超级调用,所以然后调用A1的方法;但 A1 并没有反过来调用 super,所以链停在那里。

    【讨论】:

      【解决方案2】:

      好的,回答我自己的问题:这里详细描述了让我感到困惑的事情(未能在直接继承 object 的类中调用 super()):

      https://fuhm.net/super-harmful/

      【讨论】:

        猜你喜欢
        • 2021-03-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多