Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 797
Inyoung Kim 김인영 Avatar asked Aug 28 '26 17:08

Inyoung Kim 김인영


2 Answers

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.__init__ is inherited from Child and that one does not call Parent2.__init__, because of the missing call to super().__init__.

like image 188
zvone Avatar answered Aug 31 '26 08:08

zvone


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'
like image 25
TheDude Avatar answered Aug 31 '26 07:08

TheDude



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!