DEV Community

Dhanush Kumar Sivaji
Dhanush Kumar Sivaji

Posted on Edited on Originally published at dhanushkumarsivaji.substack.com

The path to AI FDE #21: Classes, objects and dataclasses

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.

Cover card titled "Classes and objects, from Zero" for issue 21 of The Path to AI FDE by Dhanush Kumar Sivaji. Subtitle: bundle data with the actions that belong to it. Six numbered cards in two lanes. Part A, classes and objects: 1, classes, shown as class Cookie: a blueprint that bundles data and behaviour; 2, objects, shown as a = Cookie() and b = Cookie(): one concrete thing made from the blueprint; 3, __init__ and self, shown as self.balance = balance: __init__ sets up each object's data, and self means "this object". Part B, classes in practice: 4, methods, shown as asha.deposit(30): functions that belong to a class and use its data; 5, dataclasses, shown as @dataclass: writes __init__, a readable printout and == for data-holding classes; 6, when to use one: state plus behaviour, a class; just a calculation, a function; with a warning that forgetting self gives "takes 1 positional argument but 2 were given". A tip bar says a class is a blueprint, and objects are the things you make from it.


Part A · Classes and objects

Diagram titled "A class is a blueprint", subtitle: you've used them already, now make your own. Top, you already use classes: print(type("hello")), print(type((1, 2, 3))) and print("hello".upper()) print <class 'str'>, <class 'list'> and HELLO; "hello" is made from the str class, and .upper() is an action that belongs to it. Bottom left, your own blueprint: class Cookie: with pass inside, then print(Cookie), which prints <class '__main__.Cookie'>. An arrow points to three notes: class equals blueprint, like a cookie cutter that says what every cookie has (data) and can do (behaviour); pass means nothing inside yet, a placeholder so the block isn't empty; and CapitalWords, so class names look like Cookie and PiggyBank while variables and functions stay lowercase. A tip bar says a class keeps data and the actions that belong to it in one place.

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())
Enter fullscreen mode Exit fullscreen mode
<class 'str'>
<class 'list'>
HELLO
Enter fullscreen mode Exit fullscreen mode

"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)
Enter fullscreen mode Exit fullscreen mode
<class '__main__.Cookie'>
Enter fullscreen mode Exit fullscreen mode

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.

Diagram titled "One blueprint, many objects", subtitle: each call to Cookie() makes a new cookie. A dashed cookie-cutter box labelled Cookie, the class, has two arrows to two cookies: a = Cookie(), object 1, and b = Cookie(), object 2. Below, code defines class Cookie with pass, makes a and b, then prints isinstance(a, Cookie) and a is b, giving True and False. Three notes: isinstance(a, Cookie) is True because a was made from Cookie; a is b is False because two calls make two separate objects; object and instance mean the same thing. A tip bar says call the class, with brackets, to make a new object each time.

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)
Enter fullscreen mode Exit fullscreen mode
True
False
Enter fullscreen mode Exit fullscreen mode
  • isinstance(a, Cookie) asks “was a made from Cookie?” Yes.
  • a is b asks “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”.

Diagram titled "__init__ and self", subtitle: set up each object's own data as it's made. Left, piggy.py: class PiggyBank with def __init__(self, owner, balance=0) storing self.owner = owner and self.balance = balance; then asha = PiggyBank("Asha") and ravi = PiggyBank("Ravi", 50), and two prints that output Asha 0 and Ravi 50. Right, two object boxes: asha with .owner "Asha" and .balance 0; ravi with .owner "Ravi" and .balance 50; each object keeps its own attributes. Three steps below: 1, Python makes it, PiggyBank("Asha") makes a fresh, empty object; 2, __init__ runs, the new object goes in as self and "Asha" as owner, and you never pass self; 3, stored on self, self.owner = owner saves an attribute, reached with a dot as asha.owner. A tip bar says __init__ sets up each new object, and self means "this 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)
Enter fullscreen mode Exit fullscreen mode
Asha 0
Ravi 50
Enter fullscreen mode Exit fullscreen mode

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

Diagram titled "Methods belong to a class", subtitle: functions that use self to read and change the object. Left, inside class PiggyBank, under __init__: def deposit(self, amount) adds amount to self.balance; def withdraw(self, amount) raises ValueError("not enough money") if amount is more than self.balance, otherwise subtracts it; def describe(self) returns an f-string, owner has balance. Right, a method is a def in the class, whose first parameter is self so it can read and change this object's data; and a shorthand box: asha.deposit(30) means PiggyBank.deposit(asha, 30). Bottom, asha's balance step by step: PiggyBank("Asha") gives 0, .deposit(30) gives 30, .withdraw(10) gives 20, and .describe() returns "Asha has 20". An orange note says .withdraw(100) raises ValueError: not enough money; the rule lives inside the class, next to the data it protects, as in issue 19. A tip bar says methods keep the rules for changing the data next to the data.

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)
Enter fullscreen mode Exit fullscreen mode
Asha has 20
Traceback (most recent call last):
  ...
ValueError: not enough money
Enter fullscreen mode Exit fullscreen mode

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.

Diagram titled "Dataclasses", subtitle: same recipe, much less typing. Two columns. Left, a plain class Recipe with an __init__ taking name, servings and minutes=30 and three self lines; print(dal) shows <__main__.Recipe object at 0x...>, and comparing two equal-looking recipes with == gives False. Right, from dataclasses import dataclass, then @dataclass above class Recipe with three fields, name: str, servings: int and minutes: int = 30; print(dal) shows Recipe(name='Dal', servings=4, minutes=40), and == gives True. Three cards below: writes for you, __init__, a readable printout and == that compares fields; name: str is a field, a name plus a type hint, and hints are labels that Python doesn't check; a list default, tags: list = (), fails with "mutable default ... use default_factory", so write field(default_factory=list). A tip bar says for classes that mainly hold data, let @dataclass write the setup code.

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))
Enter fullscreen mode Exit fullscreen mode
Recipe(name='Dal', servings=4, minutes=40)
40
True
Recipe(name='Rice', servings=2, minutes=30)
Enter fullscreen mode Exit fullscreen mode

@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 as False, 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))
Enter fullscreen mode Exit fullscreen mode
10.0
Recipe(name='Dal', servings=8, minutes=40)
Enter fullscreen mode Exit fullscreen mode

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.

Diagram titled "When to use a class", subtitle: three questions, three answers. Each question has an arrow to its answer. 1, data that changes, plus actions that go with it, like a balance and the rules for changing it: a class, for example PiggyBank. 2, mainly named data, like a recipe, a book or a row from a JSON file: a dataclass, for example Recipe. 3, just inputs in, an answer out, with nothing to remember between calls: a function, for example c_to_f(celsius). Bottom left, an orange warning card, a function in disguise: class Adder with one method, add(self, a, b), returning a + b, with no data and one method. Bottom right, a green card, just write the function: def add(a, b) returning a + b, the same job with less to read. A tip bar says start with functions, and reach for a class when you keep passing the same values around.

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. PiggyBank has a balance and the rules for changing it.
  • Mainly named data? A dataclass. Recipe is 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))
Enter fullscreen mode Exit fullscreen mode
86.0
Enter fullscreen mode Exit fullscreen mode

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)

  1. In your sandbox folder, create books.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())
Enter fullscreen mode Exit fullscreen mode
  1. 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%)
Enter fullscreen mode Exit fullscreen mode

min(...) stops pages_read going past the last page, and :.0% (an f-string format) shows a fraction as a whole-number percentage.

  1. 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.
  2. Add a method is_finished(self) that returns True when every page is read. Print it before and after the big read(200).
  3. Delete self from def read(self, n): and run it again. Read the error (it’s in the mistakes below), then put self back.

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 self in a method. Write def deposit(amount): and call asha.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
Enter fullscreen mode Exit fullscreen mode

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

  1. 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
  2. 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
  3. Python docs, “dataclasses — Data Classes” (@dataclass adds generated methods such as __init__(), __repr__() and __eq__(); fields with defaults; mutable default values and default_factory). https://docs.python.org/3/library/dataclasses.html
  4. PEP 557, “Data Classes” (the design and reasons behind dataclasses). https://peps.python.org/pep-0557/
  5. Python docs, “Built-in Functions” (isinstance(), type(), min()). https://docs.python.org/3/library/functions.html
  6. 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
  7. 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.

Top comments (0)