Saltar al contenido
Back to home
Session 09 Python 2025-2026 1º

Interfaces and Contracts: Abstract Classes and Protocols

Consolidating the class model with formal contracts using abstract classes, composition vs inheritance, and direct application to the club project.

Key Concepts

  • What a contract means in object-oriented programming
  • Abstract classes with ABC and @abstractmethod
  • Difference between inheritance and composition
  • Duck typing in Python: implicit protocols
  • When to use an abstract class and when not to

Mandatory Part

1. First abstract class: Shape

Create an abstract class Shape that defines the contract all geometric shapes must fulfill.

from abc import ABC, abstractmethod

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

    @abstractmethod
    def perimeter(self) -> float:
        pass

    def describe(self) -> str:
        return f"Area: {self.area():.2f} | Perimeter: {self.perimeter():.2f}"

Try to instantiate Shape() directly and observe the error it produces.


2. Implement concrete classes

Create two classes that implement the Shape contract:

class Circle(Shape):
    def __init__(self, radius: float):
        self.radius = radius

    def area(self) -> float:
        return 3.14159 * self.radius ** 2

    def perimeter(self) -> float:
        return 2 * 3.14159 * self.radius


class Rectangle(Shape):
    def __init__(self, width: float, height: float):
        self.width = width
        self.height = height

    def area(self) -> float:
        return self.width * self.height

    def perimeter(self) -> float:
        return 2 * (self.width + self.height)

Instantiate both and call describe().


3. Polymorphic list with contract

Create a list with objects of different concrete classes and iterate over it calling the contract methods:

shapes: list[Shape] = [
    Circle(5),
    Rectangle(4, 6),
    Circle(3),
]

for shape in shapes:
    print(shape.describe())

Reflect: what does the contract guarantee that simple inheritance did not?


Extended Part

4. Inheritance vs composition

Refactor the student system so that statistics are no longer inside Student but in a separate GradeCalculator class that receives a list of students.

Goal: see in practice the difference between is a (inheritance) and uses a (composition).

class GradeCalculator:
    def __init__(self, students: list):
        self.students = students

    def average(self) -> float:
        total = sum(s.get_grade() for s in self.students)
        return total / len(self.students)

    def top_student(self):
        best = self.students[0]
        for s in self.students[1:]:
            if s.get_grade() > best.get_grade():
                best = s
        return best