Skip to content

Module 20 · Building Real Python Applications — topic 5 of 13

Classes and application design

Using classes to structure an application: data classes for records, service classes for behaviour, assigning responsibilities, composition and dependency injection, and keeping classes small and focused.

Beginner 12 min read·Lesson 298 of 306 in Python Programming

Learning objectives

  • Model records with dataclasses
  • Assign responsibilities to service classes
  • Compose classes with dependency injection

Definition

In application design, classes group data with the behaviour that belongs to it. Typical roles are data classes (records), service classes (business rules), repositories (storage) and controllers (user interaction), composed together.

Introduction

As the expense tracker gains budgets, storage and notifications, classes give each concept a home: Expense, ExpenseBook, Budget, Tracker.

Why it matters

Clear class responsibilities keep growing applications understandable and let parts be swapped — for example, a fake notifier in tests.

Detailed explanation

Use dataclasses for records that are mostly data: Expense(amount, category). frozen=True makes them immutable values.

Put behaviour where the data is: an ExpenseBook class knows how to add expenses and compute totals.

Give each class one responsibility. If a class name needs 'and' (ExpenseBookAndReportPrinter), split it.

Compose larger objects from smaller ones: a Tracker has a repository, a budget and a notifier.

Dependency injection passes collaborators into __init__ instead of creating them inside, so they can be replaced (a list repository in tests, a database in production).

Keep input and output out of model and service classes; let the command-line or GUI layer handle them.

Prefer composition to inheritance unless there is a genuine is-a relationship.

Start with functions and introduce classes when state and behaviour clearly belong together.

Syntax

Python
@dataclass(frozen=True)
class Expense:
amount: float
category: str
class Tracker:
def __init__(self, repo, budget, notify):
self.repo, self.budget, self.notify = repo, budget, notify
  • Dataclasses for records.
  • Services for behaviour.
  • Inject collaborators.

Code examples

A record and a collection class

Python
from dataclasses import dataclass
@dataclass
class Expense:
amount: float
category: str
class ExpenseBook:
def __init__(self):
self._items = []
def add(self, expense):
self._items.append(expense)
def total(self, category=None):
return sum(e.amount for e in self._items if category in (None, e.category))
book = ExpenseBook()
book.add(Expense(250, "food"))
book.add(Expense(40, "travel"))
book.add(Expense(120, "food"))
print(book.total(), book.total("food"))
Output
410 370

A class with one responsibility

Python
class Budget:
def __init__(self, limits):
self.limits = limits
def warnings(self, totals):
return [f"{c} over budget by {totals[c] - limit}"
for c, limit in self.limits.items() if totals.get(c, 0) > limit]
print(Budget({"food": 300, "travel": 100}).warnings({"food": 370, "travel": 40}))
Output
['food over budget by 70']

More examples

Composition and dependency injection

Python
from dataclasses import dataclass
@dataclass(frozen=True)
class Expense:
amount: float
category: str
class ListRepo:
def __init__(self):
self._items = []
def add(self, expense):
self._items.append(expense)
def all(self):
return list(self._items)
class Budget:
def __init__(self, limits):
self.limits = limits
class Tracker:
def __init__(self, repo, budget, notify):
self.repo, self.budget, self.notify = repo, budget, notify
def spend(self, amount, category):
self.repo.add(Expense(amount, category))
spent = sum(e.amount for e in self.repo.all() if e.category == category)
left = self.budget.limits.get(category, float("inf")) - spent
if left < 0:
self.notify(f"{category}: over budget by {-left}")
return left
messages = []
tracker = Tracker(ListRepo(), Budget({"food": 300}), messages.append)
print(tracker.spend(250, "food"), tracker.spend(120, "food"), tracker.spend(40, "travel"))
print(messages)
Output
50 -70 inf
['food: over budget by 70']

Step-by-step explanation

  • Tracker coordinates three collaborators it receives in __init__.
  • messages.append is passed as the notifier, so the test can see exactly what would have been shown or emailed.
  • Categories without a budget have an infinite limit, so they never trigger warnings.

Expected output

Running “Composition and dependency injection” prints exactly:

TextOutput
50 -70 inf
['food: over budget by 70']

Practical applications

  • Service classes in web back ends.
  • Swapping real email or SMS senders for fakes in tests.

Best practices

  • Use dataclasses for records.
  • One responsibility per class.
  • Inject collaborators.

Common mistakes

A god class

Avoid

class App:
# parses input, validates, stores, reports, emails, draws the UI...

Prefer

Split into Expense, ExpenseBook, Budget, Storage and a CLI layer.

One huge class is hard to understand, test and change.

Creating dependencies inside

Avoid

def __init__(self):
self.notify = EmailSender()

Prefer

def __init__(self, notify):
self.notify = notify

Hard-wired dependencies can't be replaced in tests.

Important notes

  • Protocols (typing.Protocol) can describe the interface collaborators must provide, such as an object with add() and all().

Key takeaways

  • Classes give each concept a home.
  • Records as dataclasses, behaviour in services.
  • Compose and inject collaborators.

Try it yourself

  1. 1
    Add a CategoryReport class that takes an ExpenseBook and produces a sorted summary.
  2. 2
    Write a fake repository that records every call, and use it to test Tracker.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

1 question test this exact topic. Answers and explanations are revealed after you submit.

  • AdvancedWhy pass a repository object into a service's __init__ instead of creating it inside?
Practise this topic