为什么 super(A, self).__init__() 不调用 A 的 __init__()?

Why super(A, self).__init__() doesn't call A's __init__()?

class A(object):
    def __init__(self):
        print('A.__init__()')

class D(A):
    def __init__(self):
        super(A, self).__init__()
        print('D.__init__()')

D()

输出为:

D.__init__()

这出乎我的意料。根据我的理解,super(A, self).__init__() 应该调用 A 的 ctor,因此应该打印 "A.init()".

我已经阅读了一些关于 super() 的其他问题,但我认为他们没有准确回答我的问题。

我的 python 是 3.5.3.

您没有得到预期结果的原因是因为您正在调用 A 父 class 的 __init__() 函数 -这是 object - 所以 A__init__() 永远不会被调用。您需要执行 super(D, self).__init__() 而不是调用 D 的父级 class、A:

的构造函数
>>> class A(object):
    def __init__(self):
        print('A.__init__()')


>>> class D(A):
    def __init__(self):
        super(D, self).__init__() # Change A to D
        print('D.__init__()')


>>> D()
A.__init__()
D.__init__()
<__main__.D object at 0x7fecc5bbcf60>
>>> 

此外,请注意,在 Python 3 中,您不再需要显式继承自 object。默认情况下,所有 class 都继承自 object。有关更详细的概述,请参阅 Python 2 文档中的 Section 3.3 New-style and old-style classes