Skip to content
BetaDE
Lesson 25 of 35Python

Python · Lesson 25 · 30 minutes

Inheritance – extending classes

What you'll learn

  • Let one class inherit from another
  • Override methods and extend them with super()
  • Check what an object is with isinstance()

Don’t write everything twice

Imagine you have a class Robot with a name, a battery and a status display. Now you need a delivery robot: it can do everything a robot can – and carry parcels too. Instead of writing everything again, you let the new class inherit:

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

    def introduce(self):
        return f"I am {self.name}."

class Dog(Animal):
    def bark(self):
        return "Woof!"

bello = Dog("Bello")
print(bello.introduce())
print(bello.bark())

class Dog(Animal): means: a dog is an animal. It gets all the methods of Animal for free – and can add its own.

Overriding and super()

A child class may override an inherited method, i.e. write its own version. With super() you call the parent class’s version:

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

    def introduce(self):
        return f"I am {self.name}."

class Cat(Animal):
    def __init__(self, name, favourite_food):
        super().__init__(name)
        self.favourite_food = favourite_food

    def introduce(self):
        return super().introduce() + f" I love {self.favourite_food}."

print(Cat("Luna", "tuna").introduce())

Press Steps: you can see Python jumping from Cat.introduce into Animal.introduce and back.

What is what?

isinstance() checks whether an object belongs to a class – across inheritance too:

class Vehicle: pass
class Car(Vehicle): pass
class Bike(Vehicle): pass

things = [Car(), Bike(), "ball"]
for thing in things:
    print(type(thing).__name__, isinstance(thing, Vehicle))

Remember: Inheritance fits when you can say “an X is a Y” – a dog is an animal, a delivery robot is a robot. A robot “has” a motor, on the other hand – you solve that with an attribute, not with inheritance.

Quick check

Before you start the task: what does this program print? Type your guess – then Python works it out.

class Animal:
    def sound(self):
        return "..."


class Cat(Animal):
    def sound(self):
        return "Meow"


class Fish(Animal):
    pass


print(Cat().sound(), Fish().sound())

Your task

Your turn

The class Robot is finished. Write a class DeliveryRobot that inherits from Robot. It also gets a list parcels (empty at the start) and the method load(parcel). A delivery robot carries at most 3 parcels – if it's full, load returns False, otherwise True. Override status() so that , 2 parcels is added at the end (with the real number).

class Robot:
    def __init__(self, name):
        self.name = name
        self.battery = 100

    def status(self):
        return f"{self.name}: {self.battery} %"


# Your class DeliveryRobot


delivery = DeliveryRobot("Parcelo")
delivery.load("Book")
delivery.load("Ball")
print(delivery.status())

Solve it without hints to earn a ⭐ on your progress page.

Show solution

Try it yourself first – mistakes teach you the most. Here is one possible solution:

class Robot:
    def __init__(self, name):
        self.name = name
        self.battery = 100

    def status(self):
        return f"{self.name}: {self.battery} %"


class DeliveryRobot(Robot):
    def __init__(self, name):
        super().__init__(name)
        self.parcels = []

    def load(self, parcel):
        if len(self.parcels) >= 3:
            return False
        self.parcels.append(parcel)
        return True

    def status(self):
        return super().status() + f", {len(self.parcels)} parcels"


delivery = DeliveryRobot("Parcelo")
delivery.load("Book")
delivery.load("Ball")
print(delivery.status())