Skip to content

Core Python·Lesson 16 of 67·intermediate

Classes, dunder methods and dataclasses

Bundle state with behaviour, make your objects work with len, in and == by implementing the protocols, and let dataclasses write the boilerplate for you.


In this lesson · 20 min

  • →Define classes with __init__, attributes and methods
  • →Give an object a useful __repr__, and know how it differs from __str__
  • →Implement the protocols behind len(), in, == and iteration
  • →Expose computed values with @property
  • →Model records with @dataclass instead of writing boilerplate
  • →Use inheritance and super() without overusing them

A class bundles data with the operations that belong to it. In an AI codebase that mostly means records — a chunk, a message, a retrieval result — and occasionally a component that holds configuration and does work, like a retriever or a client.

A first class

PythonPython not started

__init__ runs when you call the class. self is the instance being built, and it is the first parameter of every method — Python passes it for you at the call site.

Instance and class attributes

An attribute on the class is shared by every instance; an attribute on self belongs to one:

PythonPython not started

__repr__

The default representation tells you nothing. __repr__ should show what the object is, ideally in a form you could paste back into Python:

PythonPython not started

Write __repr__ for every class you expect to debug. __str__ is optional — without it, str() falls back to __repr__.

The protocols

len(x), x in y, x == y and for i in x are not built-in magic: each calls a method your class can implement.

PythonPython not started

Implementing __iter__ alone is enough to make an object work with for, list(), sum(), unpacking and every comprehension — the whole iteration ecosystem, from one method.

@property

A property is a method that reads like an attribute. Use it for a value derived from the state you already hold:

PythonPython not started

A property can also validate on the way in:

PythonPython not started

Dataclasses

Most classes in a data pipeline are records: some fields, a sensible __repr__, and equality by value. @dataclass writes all of that:

PythonPython not started

field(default_factory=list) is the dataclass answer to the mutable-default trap: the factory runs once per instance. A plain [] is rejected outright.

Two options worth knowing:

PythonPython not started

Inheritance

A subclass takes everything from its parent and changes what it needs. super() calls the parent’s version:

PythonPython not started

Try it yourself

Exercise 1

Make Chunk a frozen dataclass with text, doc_id and index (defaulting to 0), plus a tokens property returning the word count.

Your turnPython not started
Exercise 2

Give Transcript the four protocol methods so len(), iteration, indexing and in all work on it.

Your turnPython not started

Check yourself

Why does @dataclass reject `tags: list = []` but accept `tags: list = field(default_factory=list)`?

Check yourself

Your class defines __iter__ but not __len__. What works and what does not?

Recap

  • __init__ builds an instance; self is that instance, passed automatically.
  • Class attributes are shared; never make a mutable one stand in for instance state.
  • Give every debuggable class a __repr__. __str__ is optional and falls back to it.
  • len(), in, ==, indexing and for are protocols: __len__, __contains__, __eq__, __getitem__ and __iter__.
  • @property turns a computed value into something that reads like an attribute, and its setter is where validation belongs.
  • @dataclass writes __init__, __repr__ and __eq__; frozen=True adds immutability and hashability, and field(default_factory=...) is how mutable defaults are done.
  • Inherit only for a genuine “is a” relationship, and call super() rather than copying.