Inheritance

Inheritance lets you build a new class from an existing one. The new class is the child, and the existing one is the parent. The child can reuse the parent's methods, and it can also replace some of them.

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

    def describe(self):
        return self.name

    def wheels(self):
        return 4

class Bicycle(Vehicle):
    def __init__(self, name, gears):
        super().__init__(name)
        self.gears = gears

    def describe(self):
        return f"{self.name} ({self.gears} gears)"

    def wheels(self):
        return 2

car = Vehicle("Hatchback")
bike = Bicycle("Roadster", 8)
print(car.describe())
print(bike.describe())
print(bike.wheels())

Output:

Hatchback
Roadster (8 gears)
2

class Bicycle(Vehicle) makes Bicycle a child of Vehicle. Inside Bicycle's __init__, the line super().__init__(name) runs the parent's setup. So self.name is stored the same way for both classes. Then Bicycle stores its own extra value, self.gears.

Bicycle also defines describe and wheels again. When a child defines a method again like this, we say it overrides the parent's method. A bicycle uses its own versions, while a car still uses the parent's versions.

If the child does not define a method, it gets the parent's version unchanged. Use inheritance only when the child really is a kind of the parent. Sometimes one object just has another, like a bicycle that has a bell. A bicycle is not a kind of bell, so don't use inheritance there. Store the bell as an attribute of the bicycle instead.

In the exercise, complete the child's __init__ and override describe.