[英]Does a subclass need to initialize an empty super class?
This just came into my mind. 这才浮现在我的脑海。
class Parent:
pass
class Child(Parent):
def __init__(self):
# is this necessary?
super().__init__()
When a class inherits an empty class, do the subclass need to initialize it and why? 当一个类继承一个空类时,子类需要初始化它吗?为什么?
This is just fine: 很好:
class Parent:
# the __init__ is inherited from parent
pass
class Child(Parent):
# the __init__ is inherited from parent
pass
This is also fine: 这也很好:
class Parent:
# the __init__ is inherited from parent
pass
class Child(Parent):
def __init__(self):
# __init__ is called on parent
super().__init__()
This may seem ok, and will usually work fine, but not always: 这似乎可以,并且通常可以正常运行,但并非总是如此:
class Parent:
# the __init__ is inherited from parent
pass
class Child(Parent):
def __init__(self):
# this does not call parent's __init__,
pass
Here is one example where it goes wrong: 这是一个错误的示例:
class Parent2:
def __init__(self):
super().__init__()
print('Parent2 initialized')
class Child2(Child, Parent2):
pass
# you'd expect this to call Parent2.__init__, but it won't:
Child2()
This is because the MRO of Child2
is: Child2 -> Child -> Parent -> Parent2 -> object. 这是因为Child2
的MRO为:Child2-> Child-> Parent-> Parent2-> object。
Child2.__init__
is inherited from Child
and that one does not call Parent2.__init__
, because of the missing call to super().__init__
. Child2.__init__
是从Child
继承的,并且由于缺少对super().__init__
调用而未调用Parent2.__init__
super().__init__
。
No it isn't necessary. 不,没有必要。 It is necessary when you want the parent's logic to run as well. 当您希望父母的逻辑也要运行时,这是必要的。
class Parent:
def __init__(self):
self.some_field = 'value'
class Child(Parent):
def __init__(self):
self.other_field = 'other_value'
super().__init__()
child = Child()
child.some_field # 'value'
There is no requirement in the language that subclass need to call __init__
of superclass. 语言没有要求子类需要调用超类的__init__
。 Despite this, it is almost always needed because superclass initializes some base attributes and the subclass expects them to be initialized. 尽管如此,它几乎总是需要的,因为超类会初始化一些基本属性,而子类希望将其初始化。 So, if the superclass __init__
is empty, you don't need to call it, otherwise you need to. 因此,如果超类__init__
为空,则无需调用它,否则需要调用它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.