[英]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()
The output is: 输出为:
D.__init__()
This is unexpected to me. 这对我来说是意外的。 According to my understanding,
super(A, self).__init__()
should have called A
's ctor, thus should have printed "A. init ()". 根据我的理解,
super(A, self).__init__()
应该调用A
的ctor,因此应该打印“ A. init ()”。
I have read a few other questions about super()
but I don't think they answer my question exactly. 我已经阅读了有关
super()
其他一些问题,但我认为它们不能完全回答我的问题。
My python is 3.5.3. 我的python是3.5.3。
The reason your not getting what you expect is because you are calling the __init__()
function of A
's parent class - which is object
- so A
's __init__()
is never called. 无法获得期望的原因是因为您正在调用
A
的父类的__init__()
函数__init__()
这是object
,因此永远不会调用A
的__init__()
。 You need to do super(D, self).__init__()
instead to call the constructor of D
's parent class, A
: 您需要做
super(D, self).__init__()
来调用D
的父类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>
>>>
Also, note that in Python 3 you no longer have to explicitly inherit from object
. 另外,请注意,在Python 3中,您不再需要显式继承自
object
。 All classes inherit from object
by default. 默认情况下,所有类都从
object
继承。 See Section 3.3 New-style and old-style classes in Python 2's docs for a more detailed overview. 有关更详细的概述,请参见Python 2的文档中的3.3新风格和旧风格的类 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.