子类是否需要初始化一个空的超类?

问题描述 投票:1回答:3

这只是我的想法。

class Parent:
    pass

class Child(Parent):
    def __init__(self):
        # is this necessary?
        super().__init__()

当一个类继承一个空类时,子类是否需要初始化它,为什么?

python python-3.x
3个回答
4
投票

这很好:

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'


2
投票

不,没有必要。当您希望父级逻辑运行时,这是必要的。

__init__

1
投票

语言中没有要求子类需要调用超类的__init__。尽管如此,它几乎总是需要的,因为超类初始化了一些基本属性,而子类期望它们被初始化。所以,如果超类qazxswpoi是空的,你不需要调用它,否则你需要。

© www.soinside.com 2019 - 2024. All rights reserved.