这只是我的想法。
class Parent:
pass
class Child(Parent):
def __init__(self):
# is this necessary?
super().__init__()
当一个类继承一个空类时,子类是否需要初始化它,为什么?
这很好:
class Parent:
# the __init__ is inherited from parent
pass
class Child(Parent):
# the __init__ is inherited from parent
pass
这也没关系:
class Parent:
# the __init__ is inherited from parent
pass
class Child(Parent):
def __init__(self):
# __init__ is called on parent
super().__init__()
这似乎没问题,通常会正常工作,但并非总是如此:
class Parent:
# the __init__ is inherited from parent
pass
class Child(Parent):
def __init__(self):
# this does not call parent's __init__,
pass
这是一个出错的例子:
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()
这是因为Child2
的MRO是:Child2 - > Child - > Parent - > Parent2 - > object。
Child2.__init__
继承自Child
,并且由于缺少对Parent2.__init__
的召唤,因此不会将super().__init__
称为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'
。
不,没有必要。当您希望父级逻辑运行时,这是必要的。
__init__
语言中没有要求子类需要调用超类的__init__
。尽管如此,它几乎总是需要的,因为超类初始化了一些基本属性,而子类期望它们被初始化。所以,如果超类qazxswpoi是空的,你不需要调用它,否则你需要。