Python for AI Engineers · Part A · Lesson 5 of 26
Python classes and dataclasses for Java and JS developers
Python classes for a developer coming from Java or JavaScript: __init__ and self, class vs instance attributes, @property, dunder methods, dataclasses (default_factory, frozen, order), inheritance with super(), composition, ABCs and Protocol. You will model the messages of a chat app.
⏱ 40 min3 exercises that check your codeRuns in your browser
By the end you can
- Write a class with
__init__andself, and tell instance attributes from class attributes - Use
@property, the underscore convention, and dunder methods like__repr__,__eq__and__len__ - Replace boilerplate with dataclasses: defaults,
field(default_factory=list),frozen=Trueandorder=True - Choose between inheritance with
super()and composition, and describe an interface with an ABC or aProtocol
1A class: __init__ and self
A class starts with class Name: and its methods are defs indented inside it. There is no new keyword: you create an object by calling the class like a function, Message("user", "hi").
__init__ plays the role of a constructor. Python has already created the empty object when __init__ runs; its job is to fill it in. Every method receives that object as its first parameter, named self by convention. It is the same thing as this in Java or JavaScript, except you write it out. You never pass it yourself: m.preview() is turned into Message.preview(m) for you.
There are no field declarations. An attribute exists as soon as you assign self.role = ..., usually in __init__.
class Message:
def __init__(self, role, content):
self.role = role # creates the attribute "role" on this object
self.content = content
def preview(self, width=20):
if len(self.content) <= width:
return f"{self.role}: {self.content}"
return f"{self.role}: {self.content[:width]}..."
m = Message("user", "What is retrieval augmented generation?") # no "new"
print(m.role)
print(m.preview())
print(m.preview(width=8))
print(Message.preview(m)) # what m.preview() really does
Expected output
user user: What is retrieval au... user: What is ... user: What is retrieval au...
public class Message {
private final String role; // fields are declared up front
private final String content;
public Message(String role, String content) {
this.role = role;
this.content = content;
}
public String preview(int width) {
if (content.length() <= width) return role + ": " + content;
return role + ": " + content.substring(0, width) + "...";
}
}
Message m = new Message("user", "What is RAG?"); class Message {
constructor(role, content) {
this.role = role;
this.content = content;
}
preview(width = 20) {
if (this.content.length <= width) return `${this.role}: ${this.content}`;
return `${this.role}: ${this.content.slice(0, width)}...`;
}
}
const m = new Message("user", "What is RAG?"); Watch out Forgetting self is the first bug everyone hits. Writing def preview(width): makes Python pass the object in as width. Writing role = role inside __init__ (without self.) only creates a local variable that disappears when __init__ returns.
2Instance attributes vs class attributes
An attribute set on self belongs to one object. A variable written directly in the class body is a class attribute: one copy, shared by every object, close to a static field in Java.
When you read a.count, Python looks on the object first and then on the class. When you assign a.count = 99, it always writes on the object, so the object gets its own count that hides the class one. To change the shared value, assign through the class: Message.count += 1.
class Message:
ROLES = ("system", "user", "assistant") # class attribute: one copy for all objects
count = 0 # class attribute: how many were created
def __init__(self, role, content):
if role not in Message.ROLES:
raise ValueError(f"unknown role: {role!r}")
self.role = role # instance attribute: one per object
self.content = content
Message.count += 1 # change the shared value through the class
a = Message("user", "hi")
b = Message("assistant", "hello")
print(Message.count, a.count, b.count) # reading a.count falls back to the class
a.count = 99 # assigning creates a NEW attribute on a only
print(a.count, b.count, Message.count)
try:
Message("bot", "?")
except ValueError as e:
print(e)
Expected output
2 2 2 99 2 2 unknown role: 'bot'
Tip Python also has @staticmethod (a plain function that lives in the class) and @classmethod (receives the class as cls, often used for extra constructors like Message.from_dict(data)). Use them sparingly; a module-level function is often simpler.
Watch out Never put a list or dict in the class body for per-object data (class Chat: messages = []). It is one list shared by every chat, so users see each other's messages. Create it in __init__ instead: self.messages = []. It is the same bug as the mutable default argument from the last lesson.
3No private keyword: the underscore and @property
Python has no private or protected. Every attribute can be read and changed from outside. The convention is a leading underscore: self._messages means "internal, do not touch". Tools and other developers respect it; the language does not enforce it. (Two underscores, self.__x, renames the attribute to _ClassName__x to avoid clashes in subclasses. It is not real privacy either, and you rarely need it.)
So you do not write getX() and setX() up front. Start with a plain attribute. If you later need a check or a computed value, turn it into a @property: callers keep writing chat.max_messages, without parentheses, and your method runs instead.
class Conversation:
def __init__(self, max_messages=3):
self._messages = [] # leading underscore: internal by convention
self.max_messages = max_messages # goes through the setter below
@property
def max_messages(self): # runs on: chat.max_messages
return self._max
@max_messages.setter
def max_messages(self, value): # runs on: chat.max_messages = value
if value < 1:
raise ValueError("max_messages must be at least 1")
self._max = value
@property
def last(self): # a computed, read-only attribute
return self._messages[-1] if self._messages else None
def add(self, text):
self._messages.append(text)
if len(self._messages) > self._max:
self._messages.pop(0) # keep only the newest messages
chat = Conversation()
for text in ["one", "two", "three", "four"]:
chat.add(text)
print(chat.last, chat._messages) # _messages is readable, just "please do not"
try:
chat.max_messages = 0
except ValueError as e:
print(e)
try:
chat.last = "hack"
except AttributeError as e:
print("AttributeError:", e)
Expected output
four ['two', 'three', 'four'] max_messages must be at least 1 AttributeError: property 'last' of 'Conversation' object has no setter
Tip This trimming of old messages is a simple version of what every chat app must do: the model only accepts so many tokens of context, so the oldest turns are dropped or summarised.
4Dunder methods: __repr__, __eq__, __len__
"Dunder" means double underscore. These methods are hooks the language calls for you: print(x) and the console call __repr__ (like toString()), a == b calls __eq__ (like equals()), and len(x) calls __len__ (like size()). If a class has __len__, if chat: is false when the length is 0.
Without __repr__, printing an object shows something useless like <__main__.Conversation object at 0x7f3a...>. Without __eq__, == compares identity, like Java's == on objects. Return NotImplemented from __eq__ when the other object is a different type, so Python can try the other side and then fall back to False.
class Conversation:
def __init__(self, title):
self.title = title
self.messages = []
def add(self, role, content):
self.messages.append((role, content))
return self # returning self allows chaining
def __repr__(self): # used by print() and the console
return f"Conversation(title={self.title!r}, messages={len(self)})"
def __len__(self): # used by len() and by if/bool()
return len(self.messages)
def __eq__(self, other): # used by ==
if not isinstance(other, Conversation):
return NotImplemented
return self.messages == other.messages
a = Conversation("DNS help").add("user", "What is DNS?")
b = Conversation("Copy").add("user", "What is DNS?")
print(a)
print(len(a), bool(Conversation("empty")))
print(a == b, a is b, a == "hello")
print([a, b]) # lists show their items with __repr__
Expected output
Conversation(title='DNS help', messages=1) 1 False True False False [Conversation(title='DNS help', messages=1), Conversation(title='Copy', messages=1)]
@Override public String toString() { ... } // __repr__
@Override public boolean equals(Object o) { ... } // __eq__
@Override public int hashCode() { ... } // __hash__
public int size() { return messages.size(); } // __len__, but len(x) works on any class Watch out Defining __eq__ sets __hash__ to None, so the object can no longer go in a set or be a dict key (TypeError: unhashable type). That is on purpose: equal objects must have equal hashes. Add __hash__ only if the object never changes, or use a frozen dataclass (next sections).
5Dataclasses: the boilerplate written for you
Most classes in an AI app just hold data: a message, a document chunk, a search hit. @dataclass from the standard library reads the annotated class variables (role: str) as fields and writes __init__, __repr__ and __eq__ for you. It is close to a Java record or a Lombok @Data class.
Fields with a default must come after fields without one, just like function parameters. For a list or dict default you must use field(default_factory=list): the factory is called for each new object, so every conversation gets its own list. Writing messages: list = [] is refused with ValueError: mutable default ... use default_factory.
The type hints are not checked at run time (Message(1, 2) works). They tell readers, and your editor, what belongs there. Validation is the job of Pydantic, in the next lesson.
from dataclasses import asdict, dataclass, field
@dataclass
class Message:
role: str
content: str
tokens: int = 0 # a field with a default
@dataclass
class Conversation:
title: str
messages: list[Message] = field(default_factory=list) # a fresh list per object
def add(self, role, content): # you can still write your own methods
self.messages.append(Message(role, content, tokens=len(content.split())))
trip = Conversation("Trip plan")
trip.add("user", "Plan two days in Goa")
empty = Conversation("Empty")
print(trip)
print(empty.messages) # not shared with trip
print(Message("user", "hi") == Message("user", "hi")) # __eq__ compares the fields
print(asdict(trip)["messages"]) # plain dicts and lists, ready for JSON
Expected output
Conversation(title='Trip plan', messages=[Message(role='user', content='Plan two days in Goa', tokens=5)])
[]
True
[{'role': 'user', 'content': 'Plan two days in Goa', 'tokens': 5}]// Java 16+ record: constructor, accessors, equals, hashCode, toString
public record Message(String role, String content, int tokens) {
public Message(String role, String content) { this(role, content, 0); }
} Watch out A class variable without a type hint is not a field: tokens = 0 (no : int) becomes a plain class attribute and is left out of __init__. Always annotate dataclass fields.
6frozen=True and order=True
@dataclass(frozen=True) makes objects immutable: assigning to a field raises FrozenInstanceError. A sent chat message should never change, so this is a good fit. To get a changed copy, use dataclasses.replace(obj, field=new_value). A frozen dataclass also gets __hash__, so it can go in a set or be a dict key.
order=True adds <, <=, > and >=, comparing the fields in the order they are written, like tuples: first field first, the next one only on a tie. Put the field you want to sort by first. Here messages that arrived out of order are sorted by sent_at.
from dataclasses import FrozenInstanceError, dataclass, replace
@dataclass(frozen=True, order=True)
class Message:
sent_at: int # compared first, so sorting is by time
role: str # compared only when sent_at is equal
content: str
late = Message(3, "assistant", "DNS maps names to IP addresses.")
early = Message(1, "user", "What is DNS?")
try:
early.content = "edited"
except FrozenInstanceError as e:
print("error:", e)
fixed = replace(early, content="What is DNS, briefly?") # a new object, early is unchanged
print(early.content, "->", fixed.content)
for m in sorted([late, fixed]):
print(m.sent_at, m.role)
seen = {early, Message(1, "user", "What is DNS?")} # hashable: equal ones collapse
print(len(seen), early < late)
Expected output
error: cannot assign to field 'content' What is DNS? -> What is DNS, briefly? 1 user 3 assistant 1 True
Tip Make a dataclass frozen=True unless you have a reason not to. Immutable values are safe to cache, share between threads and use as dict keys, for example caching an embedding per text chunk.
7Inheritance and super()
A subclass names its parent in parentheses: class ToolResult(Message): is Java's extends. It inherits every method and can override one by defining it again. super() gives you the parent's version, so super().__init__(...) runs the parent constructor and super().to_api() reuses the parent's result.
Unlike Java, the parent __init__ is not called for you. If the subclass defines __init__ and forgets super().__init__(...), the parent's attributes are never set. isinstance(obj, Message) is true for a subclass too, like instanceof.
The example builds the tool message an OpenAI-style chat API expects after your code has run a tool for the model: it carries the id of the tool call it answers.
class Message:
def __init__(self, role, content):
self.role = role
self.content = content
def to_api(self):
return {"role": self.role, "content": self.content}
class ToolResult(Message): # ToolResult extends Message
def __init__(self, tool_call_id, content):
super().__init__("tool", content) # run the parent constructor first
self.tool_call_id = tool_call_id
def to_api(self): # override, reusing the parent's dict
data = super().to_api()
data["tool_call_id"] = self.tool_call_id
return data
history = [Message("user", "Weather in Pune?"), ToolResult("call_1", "31 C, sunny")]
for m in history:
print(m.to_api()) # each object runs its own to_api
print(isinstance(history[1], Message), issubclass(ToolResult, Message))
Expected output
{'role': 'user', 'content': 'Weather in Pune?'}
{'role': 'tool', 'content': '31 C, sunny', 'tool_call_id': 'call_1'}
True Trueclass ToolResult extends Message {
private final String toolCallId;
ToolResult(String toolCallId, String content) {
super("tool", content);
this.toolCallId = toolCallId;
}
@Override Map<String, Object> toApi() {
var data = new HashMap<>(super.toApi());
data.put("tool_call_id", toolCallId);
return data;
}
} 8Composition over inheritance
Inheritance says "is a": a ToolResult is a Message. Most of the time you want "has a" instead: a chat session has a model client and has a history. That is composition: you pass the parts in (usually to __init__) and call them. You can swap a part without touching the class, which is exactly how you test LLM code without a real model.
Python uses duck typing: ChatSession does not care what class the model is, only that it has a complete(messages) method. Below, a fake model that just echoes is enough to run the whole flow. In a lab you pass the real OpenAI client wrapper instead, and ChatSession does not change.
from dataclasses import dataclass, field
@dataclass(frozen=True)
class Message:
role: str
content: str
class EchoModel: # a fake model for tests
def complete(self, messages):
return "You said: " + messages[-1].content
@dataclass
class ChatSession:
model: object # has a model (any object with complete())
system: str = "You are a helpful assistant."
history: list[Message] = field(default_factory=list) # has a history
def ask(self, text):
self.history.append(Message("user", text))
messages = [Message("system", self.system), *self.history]
reply = self.model.complete(messages) # delegate to the part
self.history.append(Message("assistant", reply))
return reply
session = ChatSession(model=EchoModel())
print(session.ask("hello"))
print(session.ask("what is a token?"))
print([m.role for m in session.history])
Expected output
You said: hello You said: what is a token? ['user', 'assistant', 'user', 'assistant']
Tip Ask "is it really a kind of X, everywhere an X is used?" before you subclass. If the answer is "it uses an X", pass the X in. Deep class trees are rare in good Python code.
9Interfaces: abstract base classes and Protocol
Python has no interface keyword, but two tools fill the gap. An abstract base class (ABC with @abstractmethod) is like a Java abstract class: subclasses must inherit from it and implement the abstract methods, and Python refuses to create an object of a class that still has one missing.
A Protocol (from typing) describes a shape with no inheritance at all, like a TypeScript interface: any class with a matching complete method fits. It is checked by a type checker such as mypy or your editor, not at run time. It is the right type for the model parameter of the previous section. The ... body is Python's "no body here" placeholder.
from abc import ABC, abstractmethod
from typing import Protocol
class Tool(ABC): # abstract base class: must be subclassed
name = "tool"
@abstractmethod
def run(self, query: str) -> str: ...
class WordCount(Tool):
name = "word_count"
def run(self, query: str) -> str: # implements the abstract method
return str(len(query.split()))
class ChatModel(Protocol): # a shape, checked by type checkers only
def complete(self, messages: list) -> str: ...
class EchoModel: # does NOT inherit ChatModel, still fits it
def complete(self, messages: list) -> str:
return messages[-1]
def answer(model: ChatModel, text: str) -> str:
return model.complete([text])
try:
Tool()
except TypeError as e:
print(e)
print(WordCount().name, WordCount().run("how many words here"))
print(answer(EchoModel(), "hi"))
Expected output
Can't instantiate abstract class Tool without an implementation for abstract method 'run' word_count 4 hi
Rule of thumb: use a Protocol to describe what you need from objects others give you (a model client, a vector store). Use an ABC when you own a family of classes and want shared code plus a guarantee that every subclass implements a method, like the tools of an agent.
Common mistakes
- Leaving out
self: in the method definition (def add(text)), or in the assignment (role = roleinstead ofself.role = role). - Putting per-object data in the class body (
messages = []), so every object shares one list. Create it in__init__or usefield(default_factory=list). - Writing
getX()/setX()methods by habit. Use a plain attribute, and switch to@propertyonly when you need logic. - Defining
__eq__and then putting the objects in a set or using them as dict keys: they are now unhashable. Use@dataclass(frozen=True)for value objects. - Overriding
__init__in a subclass and forgettingsuper().__init__(...), so the parent's attributes never exist. - Subclassing to reuse code ("a ChatSession is an OpenAIClient"). Pass the client in instead: composition is easier to test and to change.
Practice
Write the code, then press Check. Your work is saved in this browser.
1Turn it into a dataclass
This Conversation shares one list between all objects and has no __init__. Rewrite it as a @dataclass with a title: str field and a messages list field that is new for each object. Keep the add(text) method.
class Conversation:
messages = []
def add(self, text):
self.messages.append(text)
c = Conversation()
c.add("hi")
print(c.messages)
Hint
Import `dataclass` and `field`, annotate `title: str`, and write `messages: list[str] = field(default_factory=list)`.
2Rank search hits
In RAG, a search returns chunks with a score. Write a frozen, ordered dataclass Chunk with fields score: float and text: str (in that order), and a function top_k(chunks, k) that returns the k chunks with the highest score, best first.
from dataclasses import dataclass
class Chunk:
pass
def top_k(chunks, k):
return chunks[:k]
Hint
Use `@dataclass(frozen=True, order=True)`. Then `sorted(chunks, reverse=True)[:k]`.
3A system message with super()
Write SystemMessage, a subclass of Message that takes only content, sets the role to "system" by calling the parent constructor, and overrides to_api() so the content is stripped of spaces at both ends (use super().to_api()).
class Message:
def __init__(self, role, content):
self.role = role
self.content = content
def to_api(self):
return {"role": self.role, "content": self.content}
class SystemMessage(Message):
pass
Hint
In `__init__(self, content)` call `super().__init__("system", content)`. In `to_api`, take `data = super().to_api()` and replace `data["content"]` with `data["content"].strip()`.
Interview questions
Q1What is self in Python?
The object a method was called on, passed automatically as the first parameter. obj.method(x) is run as Class.method(obj, x). It is the same as this in Java, but explicit: you must list it in every instance method and use it to reach attributes.
Q2What is the difference between a class attribute and an instance attribute?
A class attribute is defined in the class body and shared by all objects, like a static field. An instance attribute is set on self and belongs to one object. Reading falls back from the object to the class; assigning on an object always creates an instance attribute.
Q3How do you make an attribute private in Python?
You cannot enforce it. A single leading underscore marks it as internal by convention. A double underscore triggers name mangling (_Class__x), which avoids clashes in subclasses but is not security. Use @property to control reads and writes behind a normal attribute name.
Q4What does @dataclass generate, and what do frozen and order do?
From the annotated fields it generates __init__, __repr__ and __eq__. frozen=True blocks assignment after creation and adds __hash__. order=True adds <, <=, >, >= comparing fields as a tuple in definition order. Mutable defaults need field(default_factory=...).
Q5Why does defining __eq__ make an object unhashable?
Objects that are equal must have the same hash. Python cannot know a hash that matches your __eq__, so it sets __hash__ to None. Define __hash__ from the same fields only if the object is immutable, or use a frozen dataclass.
Q6ABC or Protocol: which would you use?
An ABC requires subclasses to inherit from it and is enforced at run time when you create an object. A Protocol is structural, like a TypeScript interface: any class with the right methods fits, checked by a static type checker. Protocol suits dependencies you receive, such as a model client; an ABC suits a family of classes you own.