Inheritance

Inheritance#

Sometimes we do not want to create a new class from scratch. We want to create a new class that is based on an existing class. This is called inheritance. The new class is called a subclass or child and the existing class is called a superclass or parent. The subclass inherits all the attributes and functions of the superclass. The subclass can also have its own attributes and functions.

The Superclass#

Classic examples of this are animal, person and vehicle. For example from an animal we can create multiple subclasses like dog, cat, bird, fish etc. Each of these subclasses will have their own attributes and functions but they will also have the attributes and functions of the superclass animal.

class Animal:
    def __init__(self, legs, eyes):
        self.legs = legs
        self.eyes = eyes
        
    def dance(self):
        return f"I am dancing with my {self.legs} legs and my {self.eyes} eyes"

Now we can create an instance of animal:

unicorn = Animal(4, 2)
print(unicorn.dance())
I am dancing with my 4 legs and my 2 eyes

The Subclass#

This can be something more specific. For example a spider:

class Spider(Animal):
    def __init__(self, legs, eyes, webs):
        super().__init__(legs, eyes)
        self.webs = webs

Now, what is going on here:

  • class Spider(Animal): - this is how we define that Spider is a subclass of Animal

  • super().__init__(legs, eyes) - this is how we call the constructor of the superclass. This is necessary because we want to use the attributes of the superclass

  • self.webs = webs - this is how we define the new attribute of the subclass

spidy = Spider(8, 8, 12)

Now we can make spidy dance:

print(spidy.dance())
I am dancing with my 8 legs and my 8 eyes

But we can also make spidy do something that only spiders can do:

class Spider(Animal):
    def __init__(self, legs, eyes, webs):
        super().__init__(legs, eyes)
        self.webs = webs
        self.flies = 0
        
    def catch_fly(self):
        self.flies += 1
        return f"I am catching a fly with my {self.webs} webs"

We gave the spider a new attribute flies and a new function catch_fly. When we create an instance of the spider we can see that the number of flies is 0:

spidy = Spider(8, 8, 12)
print(spidy.flies) # this is how we can access the attribute flies
0

Now we can make spidy catch a fly:

print(spidy.catch_fly())
I am catching a fly with my 12 webs

And we can see that the number of flies is now 1:

print(spidy.flies)
1

Each time we call the function catch_fly the number of flies will increase by 1:

spidy.catch_fly()
print(spidy.flies)
2