Story – Python Inheritance

After gaining a solid understanding of classes and objects, Alex wanted to learn more about Python inheritance. He had heard that it was a powerful feature of object-oriented programming that could make his code more efficient and easier to maintain.

To start, Alex created a new class called Vehicle that would serve as the parent class for both the Car and Motorcycle classes he had previously created. The Vehicle class had common attributes such as make, model, and year, as well as methods to display information and make sounds.

class Vehicle:
    def __init__(self, make, model, year):
        self.make = make
        self.model = model
        self.year = year

    def display_vehicle_info(self):
        print(f"This is a {self.year} {self.make} {self.model}.")py

    def make_sound(self):
        print("Vroom!")

Next, Alex modified the Car and Motorcycle classes to inherit from the Vehicle class. He did this by including the name of the parent class in parentheses after the child class name.

class Car(Vehicle):
    def __init__(self, make, model, year, color):
        super().__init__(make, model, year)
        self.color = color

class Motorcycle(Vehicle):
    def __init__(self, make, model, year, style):
        super().__init__(make, model, year)
        self.style = style

    def make_sound(self):
        print("Vroom vroom!")

Alex then created instances of the Car and Motorcycle classes and called their methods.

my_car = Car("Toyota", "Corolla", 2020, "blue")
my_motorcycle = Motorcycle("Honda", "CBR600RR", 2019, "sport")

my_car.display_vehicle_info()
my_car.make_sound()

my_motorcycle.display_vehicle_info()
my_motorcycle.make_sound()

The output was:

This is a 2020 Toyota Corolla.
Vroom!
This is a 2019 Honda CBR600RR.
Vroom vroom!

Alex was amazed at how easy it was to create a parent class with common attributes and methods, and then have child classes inherit from it. He could see how this would be useful for organizing code and avoiding repetition.

He continued to experiment with inheritance, creating more complex class hierarchies and exploring the various ways in which inheritance could be used to improve his code.