Shee
Shee

Reputation: 153

Do I need to always need to use init in a child class to instantiate the parent as the code still runs?

Do I always need to instantiate the parent class as well for this example because it still works when I remove it?

class Person:
    def __init__(self, name):
        self.name = name    

    @property
    def name(self):
        return self._name

    @name.setter
    def name(self, value):
        self._name = value


class SubPerson(Person):

    # Do I need this an init call? If I remove this init call, it still runs
    def __init__(self, name):
        super().__init__(name)

    @property
    def name(self):
        return super().name 

    @name.setter
    def name(self, value):
        return super(SubPerson, SubPerson).name.__set__(self, value)


s = SubPerson("John") 
print(s.name) //John

Thank you!

Upvotes: 7

Views: 2257

Answers (2)

Samarth Vashist
Samarth Vashist

Reputation: 1

Generally, the __init__ function will be defined in the subclass when there are extra attributes that need to be initialized than the ones defined in the __init__ method of the superclass or if we want to override the default superclass initialization. In this case, since the subclass doesn't have any more attributes than the parent, it is unnecessary to add the __init__ function in the subclass.

Upvotes: 0

Adam Smith
Adam Smith

Reputation: 54173

Absolutely not. The typical pattern is that the child might have extra fields that need to be set that the parent does not have, but if you omit the __init__ method completely then it inherits it from the parent which is the correct behavior in your case.

Upvotes: 8

Related Questions