New to Python and was curious if someone could explain, in layman's terms as much as possible, why it is that, when you're creating a subclass, you still need to call the parent initialization function?
Let's say you have a parent class like this:
class Pet(object):
def __init__(self, name, species):
self.name = name
self.species = species
def getName(self):
return self.name
def getSpecies(self):
return self.species
def __str__(self):
return "%s is a %s" % (self.name, self.species)
Then I want to make a subclass called "Dog" that obviously uses some of the functions in the parent class. My research is telling me that I need to do something like this:
class Dog(Pet):
def __init__(self, name, chases_cats):
Pet.__init__(self, name, "Dog")
self.chases_cats = chases_cats
def chasesCats(self):
return self.chases_cats
But why, if I'm passing the parent class as an argument when defining the subclass, do I need to call the parent's __init__
? Isn't this automatically passed to the subclass by virtue of the fact that it's a subclass?
I'm sure I'm missing something obvious here in my understanding, but it's just not clicking for me.