Python Abstract Classes · Exercises
Object-Oriented Python

Python Abstract Classes Exercises

4 exercises that build on the Python Abstract Classes (ABC) lesson, from easy to hard. Each one is checked in your browser when you press Check. Stuck? Use the hint before peeking at the solution.

What this lesson covers: An abstract class is a base class that lists the methods every child must provide without saying how they work, and Python refuses to create objects from it until all of those methods have real code. By the end you can define an abstract base class with ABC and @abstractmethod, explain why it cannot be instantiated, write subclasses that implement every abstract method, share code through concrete and template methods, declare an abstract property, and decide between an ABC and duck typing. You will practise: Write an abstract Greeter; Predict the notifier; Fix the shape that stays abstract; Build a report with the template method.

0 / 4 completed

Python Abstract Classes practice exercises

1. Write an abstract Greeter

Write code Easy

Create an abstract class Greeter with one abstract method greet(self, name). Then write two children:

  • FormalGreeter, whose greet returns "Good day, <name>."
  • CasualGreeter, whose greet returns "Hey <name>!"

For example CasualGreeter().greet("Ben") returns "Hey Ben!".

Your code
from abc import ABC, abstractmethod

# 1. class Greeter(ABC) with an abstract greet(self, name)

# 2. class FormalGreeter(Greeter): greet returns "Good day, <name>."

# 3. class CasualGreeter(Greeter): greet returns "Hey <name>!"

2. Predict the notifier

Predict the output Medium

One abstract class, two children. Type exactly what the program prints.

Read this code
from abc import ABC, abstractmethod

class Notifier(ABC):
    @abstractmethod
    def send(self, text):
        pass

    @abstractmethod
    def channel(self):
        pass

    def notify(self, text):
        return f"[{self.channel()}] {self.send(text)}"

class EmailNotifier(Notifier):
    def send(self, text):
        return text.upper()

    def channel(self):
        return "email"

class HalfNotifier(Notifier):
    def send(self, text):
        return text

try:
    HalfNotifier()
    print("half created")
except TypeError:
    print("half is abstract")

print(EmailNotifier().notify("hi"))
print(sorted(HalfNotifier.__abstractmethods__))
print(isinstance(EmailNotifier(), Notifier))

3. Fix the shape that stays abstract

Fix the bug Medium

Square should be a working Shape, and the program should print area=9, perimeter=12. Instead it prints Square is still abstract. Find the problem in Square and fix it. Do not change Shape.

Your code
from abc import ABC, abstractmethod

class Shape(ABC):
    @abstractmethod
    def area(self):
        pass

    @abstractmethod
    def perimeter(self):
        pass

    def describe(self):
        return f"area={self.area()}, perimeter={self.perimeter()}"

class Square(Shape):
    def __init__(self, side):
        self.side = side

    def area(self):
        return self.side ** 2

    def perimiter(self):
        return 4 * self.side

try:
    print(Square(3).describe())
except TypeError:
    print("Square is still abstract")

4. Build a report with the template method

Write code Hard

Use the template method pattern to build a small report system.

  1. Report(ABC): __init__(self, title) stores self.title. It has one abstract method body(self) that returns a list of text lines, and a concrete method render(self) that returns one string made of the title, then a line of - characters as long as the title, then every line from body(), each on its own line (join them with "\n").
  2. SalesReport(Report): __init__(self, sales) takes a dict that maps day to amount, calls super().__init__("Sales") and stores the dict. body() returns one line per day such as "Mon: 5", in the dict's order.

For example SalesReport({"Mon": 5, "Tue": 7}).render() returns "Sales\n-----\nMon: 5\nTue: 7".

Your code
from abc import ABC, abstractmethod

# 1. class Report(ABC): __init__(title), abstract body(), concrete render()

# 2. class SalesReport(Report): __init__(sales), body()

Next lessonPython Dataclasses

More Python Abstract Classes (ABC) examples · All Python exercises