Python, from Zero, for AILesson 60 of 89

Module 7 · Objects, generators and the shape a larger program takes

Classes: when a dict stops being enough

In this lesson

  • 9 min read
  • 6 reading sections
  • Knowledge check
  • Lesson 1 of 10 in this chapter

This chapter’s goalRestructure a growing script into classes and dataclasses with a swappable provider behind one interface, implement the dunder methods that let your objects work with for, len, in and with, write a decorator that retries or caches, run a type checker and act on its output, make the project installable as a command with pyproject.toml, and profile it to say from measurement rather than guesswork where the time goes.

This chapter’s media

The film explains chapter ideas. The audiobook narrates the complete teaching text.

FormatEnglishहिंदी
Chapter filmWatch1:40Not available
Full audiobookNot availableNot available

A little at a time

Explore an idea, try it, then check what stays.

Step 1 of 8Free · no account needed
Lesson steps

The dict that grew

You have been representing a conversation as a list of dicts, which works. Then you need to know its total token count, trim it when it gets long, save it, and reload it. Each of those is a function that takes the list, and the functions start to need each other, and you find yourself passing around a list, a token count, a model name and a file path together, always together. That is the signal. Data that always travels with the same functions wants to be an object.

Python
class Conversation:
    def __init__(self, model, system=None):
        self.model = model
        self.messages = []
        if system:
            self.messages.append(
                {"role": "system", "content": system}
            )

    def add(self, role, text):
        self.messages.append(
            {"role": role, "content": text}
        )

    def last(self):
        return (
            self.messages[-1]["content"]
            if self.messages
            else None
        )

    def __repr__(self):
        return (
            f"Conversation(model={self.model!r}, "
            f"turns={len(self.messages)})"
        )
Python
c = Conversation("gpt-4o-mini", system="Be brief.")
c.add("user", "What is a class?")
print(c)                      # Conversation(model='gpt-4o-mini', turns=2)
print(c.last())

Your place and first choices stay on this browser. Classroom credit is recorded separately.

Stuck on something?Ask Divya, your AI tutor

How to cite: Addaly (2026) ‘Classes: when a dict stops being enough’, in Python, from Zero, for AI. Edited by M. Mun. Addaly. Available at: https://addaly.com/learn/python-for-ai/classes-and-objects (Accessed: 21 November 2026).