Originally published on my newsletter, The Path to AI FDE. Subscribe free to get each issue by email.
This is a “From Zero” issue. So far your data and your functions have lived apart: a dictionary over here, a function that changes it over there. That works, but as a program grows you start passing the same five values into every function. A class lets you bundle the data with the actions that belong to it.
Think of a cookie cutter and the cookies it makes. The cutter is the class, the blueprint. Each cookie is an object made from it: same shape, its own sprinkles. By the end you’ll have a toy reading tracker built from a dataclass, and you’ll know when a class is overkill.
Part A · Classes and objects
1. A class is a blueprint that bundles data and behaviour. You’ve been using classes since #14 without the name. Try this:
print(type("hello")) print(type([1, 2, 3])) print("hello".upper()) <class 'str'> <class 'list'> HELLO "hello" is made from the str class, and [1, 2, 3] from the list class. Each class knows what data it holds (the letters, the items) and what it can do (.upper(), .append()). That’s the whole idea: data and the actions that belong to it, in one place.
Now make your own. Save cookie.py:
class Cookie: pass print(Cookie) <class '__main__.Cookie'> class Cookie: starts the blueprint. pass means “nothing inside yet”. __main__ is the name of the file you ran (#20). By convention, class names use CapitalWords (Cookie, PiggyBank), while variables and functions stay lowercase.
2. An object (or instance) is one concrete thing made from the blueprint. You make one by calling the class, with brackets, like a function:
class Cookie: pass a = Cookie() b = Cookie() print(isinstance(a, Cookie)) print(a is b) True False -
isinstance(a, Cookie)asks “wasamade fromCookie?” Yes. -
a is basks “are these the very same object?” No: two calls, two cookies.
“Object” and “instance” mean the same thing. You’ll hear “an instance of Cookie“ just as often as “a Cookie object”.
3. __init__ sets up an object’s data, and self means “this object”. An empty cookie isn’t much use. Most classes have a special method called __init__ (two underscores each side) that runs every time you make an object. Save piggy.py:
class PiggyBank: def __init__(self, owner, balance=0): self.owner = owner self.balance = balance asha = PiggyBank("Asha") ravi = PiggyBank("Ravi", 50) print(asha.owner, asha.balance) print(ravi.owner, ravi.balance) Asha 0 Ravi 50 When you write PiggyBank("Asha"), Python makes a fresh, empty object, then calls __init__ with that object as the first argument, self, and "Asha" as owner. You never pass self yourself; Python does it.
self.owner = owner stores the value on that object. Values stored this way are called attributes, and you reach them with a dot: asha.owner. Asha’s balance and Ravi’s balance are separate, because each object has its own self.
Part B · Classes in practice
4. Methods are functions that belong to a class. A method is a def inside the class. Its first parameter is always self, so it can read and change this object’s data. Add three to piggy.py:
class PiggyBank: def __init__(self, owner, balance=0): self.owner = owner self.balance = balance def deposit(self, amount): self.balance += amount def withdraw(self, amount): if amount > self.balance: raise ValueError("not enough money") self.balance -= amount def describe(self): return f"{self.owner} has {self.balance}" asha = PiggyBank("Asha") asha.deposit(30) asha.withdraw(10) print(asha.describe()) asha.withdraw(100) Asha has 20 Traceback (most recent call last): ... ValueError: not enough money The balance goes 0, then 30, then 20. The last line asks for more than there is, so withdraw raises the error you learned to write in #19. The rule “you can’t take out more than you have” now lives inside the class, next to the data it protects, instead of being repeated everywhere a balance changes.
asha.deposit(30) is shorthand for PiggyBank.deposit(asha, 30). That’s where self comes from.
5. @dataclass writes the setup code for classes that mainly hold data. Lots of classes are mostly a bundle of named values: a recipe, a book, a row from a JSON file. Writing __init__ with a self.x = x line per value gets dull. Python’s dataclasses module writes it for you:
from dataclasses import dataclass @dataclass class Recipe: name: str servings: int minutes: int = 30 dal = Recipe("Dal", 4, 40) print(dal) print(dal.minutes) print(dal == Recipe("Dal", 4, 40)) print(Recipe("Rice", 2)) Recipe(name='Dal', servings=4, minutes=40) 40 True Recipe(name='Rice', servings=2, minutes=30) @dataclass is a decorator: a line starting with @ that adds features to whatever sits under it. Each line like name: str is a field: a name plus a type hint (#14). minutes: int = 30 gives a default. From these lines, the decorator writes three things for you:
- an
__init__that takes the fields in order; - a readable printout,
Recipe(name='Dal', ...), instead of something like<__main__.Recipe object at 0x...>; - an
==that compares the fields. A plain class with the same values compares asFalse, because it only checks “same object?”.
The type hints are labels for you and your editor. Python doesn’t check them: Recipe("Dal", "four") still runs. (Pydantic, later in this series, does check them.)
Dataclasses can have methods too:
from dataclasses import dataclass @dataclass class Recipe: name: str servings: int minutes: int = 30 def per_serving(self): return round(self.minutes / self.servings, 1) def scaled(self, people): return Recipe(self.name, people, self.minutes) dal = Recipe("Dal", 4, 40) print(dal.per_serving()) print(dal.scaled(8)) 10.0 Recipe(name='Dal', servings=8, minutes=40) One trap: a list as a default. tags: list = [] fails straight away with ValueError: mutable default <class 'list'> for field tags is not allowed: use default_factory. Python is protecting you from every recipe sharing one list. Write tags: list = field(default_factory=list) instead (import field next to dataclass), and each recipe gets its own empty list.
6. Use a class for things with state and behaviour. A plain function is fine otherwise. “State” means data that changes over time, like a balance. Ask three questions:
- Data that changes, plus actions that go with it? A class.
PiggyBankhas a balance and the rules for changing it. - Mainly named data? A dataclass.
Recipeis a labelled bundle with a helper or two. - Just inputs in, answer out? A function.
c_to_f(celsius)from #20 needs no class:
def c_to_f(celsius): return celsius * 9 / 5 + 32 print(c_to_f(30)) 86.0 A good sign you need a class: you keep passing the same three or four values into every function. A good sign you don’t: your class has only __init__ and one method, or no data at all. Start with functions. Reach for a class when the code asks for one.
Try it (15 minutes)
- In your
sandboxfolder, createbooks.py:
from dataclasses import dataclass @dataclass class Book: title: str author: str pages: int pages_read: int = 0 def read(self, n): self.pages_read = min(self.pages, self.pages_read + n) def progress(self): return f"{self.title}: {self.pages_read}/{self.pages} pages ({self.pages_read / self.pages:.0%})" book = Book("The Tiny Robot", "A. Writer", 120) print(book) book.read(30) print(book.progress()) book.read(200) print(book.progress()) - Run
python3 books.py. You should see:
Book(title='The Tiny Robot', author='A. Writer', pages=120, pages_read=0) The Tiny Robot: 30/120 pages (25%) The Tiny Robot: 120/120 pages (100%) min(...) stops pages_read going past the last page, and :.0% (an f-string format) shows a fraction as a whole-number percentage.
- Make a second book and read some of it. Check that the first book’s progress didn’t change: each object has its own data.
- Add a method
is_finished(self)that returnsTruewhen every page is read. Print it before and after the bigread(200). - Delete
selffromdef read(self, n):and run it again. Read the error (it’s in the mistakes below), then putselfback.
Check your understanding: (a) What’s the difference between a class and an object? (b) What is self inside a method? (c) Name two things @dataclass writes for you.
Answer: (a) A class is the blueprint; an object is one thing made from it by calling the class, like Book(...). (b) The object the method was called on: in book.read(30), self is book. (c) Any two of: __init__, a readable printout, and == that compares the fields.
Common beginner mistakes
- Forgetting
selfin a method. Writedef deposit(amount):and callasha.deposit(30), and Python passes two things (the object and 30) into a method that accepts one:
TypeError: PiggyBank.deposit() takes 1 positional argument but 2 were given Read “takes 1 but 2 were given” in a method call as “I forgot self“. - Forgetting self. in front of the data. Inside a method, balance += amount means a local variable called balance, not the object’s. Python 3.13 says UnboundLocalError: cannot access local variable 'balance' where it is not associated with a value. Write self.balance. - Turning everything into a class. A class with no data, or with one method, is usually a function in disguise: class Adder with def add(self, a, b) is just def add(a, b). - Forgetting the brackets: asha = PiggyBank (no brackets) gives you the blueprint itself, not a new object. - A list default in a dataclass without field(default_factory=list).
Takeaway
A class is a blueprint; calling it makes objects, each with its own data. __init__ sets that data up, self means “this object”, and methods are functions that belong to the class. @dataclass writes __init__, a readable printout and == for classes that mainly hold data. Use a class for state plus behaviour, and a plain function for everything else.
Where this fits in my roadmap: this is the last new building block of my Python on-ramp. AI code is full of classes you’ll use rather than write: HTTP clients, model SDK clients, and data models that check their fields. Knowing what an object, an attribute and a method are makes all of them readable. Next issue: a one-page Python cheat sheet, with every piece from this section in one small program.
Over to you: what’s the first thing you’d model as a class? Reply with one line (nothing private).
Sources
- Python tutorial, “Classes” (”Classes provide a means of bundling data and functionality together”; class definitions, class objects, instance objects; the
__init__()method; “the instance object is passed as the first argument of the function”). https://docs.python.org/3/tutorial/classes.html - Python tutorial, “Classes”, Random Remarks (”Often, the first argument of a method is called
self. This is nothing more than a convention”). https://docs.python.org/3/tutorial/classes.html#random-remarks - Python docs, “
dataclasses— Data Classes” (@dataclassadds generated methods such as__init__(),__repr__()and__eq__(); fields with defaults; mutable default values anddefault_factory). https://docs.python.org/3/library/dataclasses.html - PEP 557, “Data Classes” (the design and reasons behind dataclasses). https://peps.python.org/pep-0557/
- Python docs, “Built-in Functions” (
isinstance(),type(),min()). https://docs.python.org/3/library/functions.html - PEP 8, “Style Guide for Python Code”, Class Names (”Class names should normally use the CapWords convention”). https://peps.python.org/pep-0008/#class-names
- Python glossary (”object”, “decorator”, “method”). https://docs.python.org/3/glossary.html
All examples are made up and were run with Python 3.13 on Nov 2, 2026. Error messages are from Python 3.13; other versions word some of them differently. Sources checked Nov 2, 2026.
Free: the 5-page roadmap from Novice to AI FDE.
If this was useful, subscribe to The Path to AI FDE for the next issue.






