Skip to main content
 首页 » 编程设计

python之子类是否需要初始化一个空的父类(super class)

2025年05月04日12txw1958

我刚想到这个。

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__.