Inheritance

Inheritance

A class can build on another class. The new class inherits everything the base class defines, and adds or replaces what it needs:

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

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


class Motorcycle(Vehicle):
    def __init__(self, name):
        super().__init__(name, 2)

class Motorcycle(Vehicle): makes Motorcycle a subclass of Vehicle. Its __init__ calls super().__init__(...) — the base class's __init__ — to do the storing, fixing wheels at 2. describe is not redefined, so the inherited one is used:

bike = Motorcycle("Vespa")
print(bike.describe())

Output:

Vespa has 2 wheels

A subclass can also override a method by defining one with the same name; calls on the subclass then use the new version.

Inheritance is the last tool in this course, and the one to reach for last: use it when one type genuinely is a special case of another. When two classes merely share a bit of code, a shared plain function is simpler.

Exercise

The starter code defines Vehicle as above.

  1. Define a class named Truck that inherits from Vehicle.
  2. Its __init__ takes name and cargo (kilograms of capacity). It calls the base __init__ with 6 wheels and stores cargo as an attribute.
  3. Override describe to return <name> has 6 wheels and carries <cargo> kg.

Truck("Scania", 18000).describe() returns "Scania has 6 wheels and carries 18000 kg".

Run your code to see the output, then press Submit.

Tests

import unittest


class TestTruck(unittest.TestCase):
    def test_truck_is_a_vehicle(self):
        self.assertIsInstance(Truck("Scania", 18000), Vehicle)

    def test_truck_has_6_wheels(self):
        self.assertEqual(Truck("Scania", 18000).wheels, 6)

    def test_cargo_is_stored(self):
        self.assertEqual(Truck("Scania", 18000).cargo, 18000)

    def test_describe_is_overridden(self):
        self.assertEqual(
            Truck("Scania", 18000).describe(),
            "Scania has 6 wheels and carries 18000 kg",
        )

    def test_base_vehicle_describe_is_unchanged(self):
        self.assertEqual(Vehicle("Vespa", 2).describe(), "Vespa has 2 wheels")
class Vehicle:
    def __init__(self, name, wheels):
        self.name = name
        self.wheels = wheels

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


class Truck(Vehicle):
    def __init__(self, name, cargo):
        super().__init__(name, 6)
        self.cargo = cargo

    def describe(self):
        return f"{self.name} has {self.wheels} wheels and carries {self.cargo} kg"


truck = Truck("Scania", 18000)
print(truck.describe())
Solution hidden. Give it a real try first.

Sign in to join the discussion.

No comments yet. Be the first to ask a question.

main.py
Console
Press Run to execute your code, or Submit to test and complete this problem.