By the end of this lesson
Create independent instances and use a small dataclass.
Before you start
- Python 3.12 or a compatible newer Python 3 interpreter; no external packages.
- Complete lesson 11 in this route, or be comfortable with its examples.
Three words to know
- Class
- A definition used to create objects with related attributes and methods.
- Instance
- One object created from a class.
- Attribute
- A value accessed on an object with a dot.
1. Keep state per instance
self refers to the instance receiving a method call. Assigning self.completed in __init__ creates instance state. Two instances can therefore change independently. Keep mutable state off class-level attributes unless sharing it is intentional.
class Progress:
def __init__(self):
self.completed = 0
def finish_one(self):
self.completed += 1
a = Progress()
b = Progress()
a.finish_one()
print(a.completed, b.completed)
What you should see · example output
1 0
2. A dataclass describes a small record
dataclass supplies common record methods from annotated fields. An annotation documents intent but does not automatically enforce the type at runtime. This example still needs input validation if populated from an untrusted file.
from dataclasses import dataclass
@dataclass
class Task:
title: str
status: str = "open"
task = Task("Read the lesson")
print(task.title)
print(task.status)
What you should see · example output
Read the lesson open
3. Prefer the simplest useful structure
A dictionary is a good fit for decoded JSON; a dataclass can make an internal record clearer; a plain function is often enough for a transformation. Inheritance, descriptors and advanced object models are outside this foundations route. Knowing when a class is unnecessary is as useful as knowing how to write one.
YOUR TURN
A small check before you continue
Create two Task instances and change the status of only the first. Will the second change? Do the str annotations reject Task(123)?
Show a suggested answer
The second status remains open. The annotations alone do not reject 123. Validate external inputs explicitly; do not mistake an annotation for a runtime check.
Sources and scope
Documentation and examples reviewed 2026-10-18. Provider screens, package versions and output wording can differ. Examples show expected outcomes; they are not a claim that OpenViST connected to your server or verified your setup.
