Read classes and dataclasses
You have already kept related values in a dictionary. The previous chapter also gave you a function that checked file data. As a solution grows, you will often meet a class, a definition used to create objects with related data and behaviour.
We will give one chapter record a class, trace a method call and compare it with a dataclass. By the end, you should be able to:
- Find the data belonging to one object.
- Explain which object a method receives as
self. - Check what a dataclass generates and what its options leave unprotected.
These skills let you review behaviour the AI has supplied, including behaviour you cannot see written out by hand.
Follow one object from creation to use
A dictionary already keeps related values together. A class can also give those values named operations:
Think of an admission form: the form's layout is shared, but each completed form holds one student's details. Similarly, a class describes a kind of object, while each instance can carry its own values. A method adds something a paper form cannot do itself: executable behaviour using those values.
class Chapter:
def __init__(self, title, lesson_count):
self.title = title
self.lesson_count = lesson_count
def label(self):
return f"{self.title}: {self.lesson_count} lessons"
chapter = Chapter("Python and Roots", 7)
print(chapter.label())
This displays Python and Roots: 7 lessons.
Chapter is the class. Chapter("Python and Roots", 7) creates an instance, one object made from that class. During its creation, __init__ receives that object as self and stores two attributes, values attached to the object.
self is the conventional parameter name for the instance a method is using. It is not a secret global variable. In self.title = title, the left-hand side stores an attribute on the object; the right-hand side reads the parameter supplied to the call.
The indented label function is a method. When you write chapter.label(), Python supplies chapter as its first argument. That is why you do not write chapter.label(chapter) yourself.
Create a second instance and it can hold a different title and count. A class is not a single shared record. However, a mutable class-level value can be shared, which brings back the same copying problem you met with lists.
Separate instance data from shared class data
Consider:
class ReadingList:
titles = []
That list belongs to the class. Different instances can find and modify the same list through it. If each reading list needs independent titles, replace that definition with this version, which creates the list for each instance:
class ReadingList:
def __init__(self):
self.titles = []
The difference is where the list is created and stored. Do not accept “it is inside a class” as proof that data is isolated. Trace the object being changed, just as you did in the shared-list example.
A class can be useful when several operations depend on the same data. A plain function and a dictionary may be clearer for a small task. Ask which responsibility the class makes easier to explain; a larger structure is not automatically better engineering.
Recognise the methods a dataclass supplies
Some classes mainly hold data. Python's dataclasses module can generate routine methods for them. The following is an alternative Chapter definition, replacing the earlier one for this comparison. Run it separately; it does not keep the earlier label method:
from dataclasses import dataclass
@dataclass(frozen=True)
class Chapter:
title: str
lesson_count: int
chapter = Chapter("Python and Roots", 7)
print(chapter.title)
The @dataclass(...) line applies a decorator, an operation that receives and changes or replaces a definition. Here, it supplies methods such as initialisation and comparison based on the declared fields. We will follow the decorator mechanism itself in Lesson 3.
title: str and lesson_count: int are type annotations, descriptions of the expected types. They let tools and readers understand the shape. They do not make a normal dataclass validate each value at runtime. In the next lesson, we will prove that distinction rather than rely on the appearance of the declaration.
You no longer see an explicit __init__, but one is generated. When reading a dataclass, inspect its fields and its decorator options to understand the methods it receives.
With frozen=True, assigning a new value to a field normally raises FrozenInstanceError. This helps prevent accidental reassignment:
chapter.title = "A different title"
That line is a deliberate failing case for the frozen dataclass above. The exception is the result to expect. It is not a request to remove the protection until the code runs.
Check the limit of frozen data
Frozen does not mean every contained object becomes immutable. Here is a third, separate version of ReadingList, using the dataclass import above. Replace the previous ReadingList definition when trying it. Its field cannot normally be rebound, but the list's contents can still change:
@dataclass(frozen=True)
class ReadingList:
titles: list[str]
reading = ReadingList(["Python and Roots"])
reading.titles.append("Python and Branches")
list[str] describes a list intended to contain strings. The final line changes the list itself, not which list the titles field refers to. It therefore still succeeds. A tuple can avoid this particular list mutation when its elements are themselves suitable immutable values.
Another option you may see is slots=True, which limits the ordinary per-instance attribute layout. It can prevent accidental extra attributes and affect memory use. It does not turn a class into an input validator or make its contained values safe. At this stage, recognise the option and check its purpose rather than adding it to every class by habit.
This matters at a tool boundary. A chapter object can be convenient after data has been checked, but the existence of its class says nothing about the caller's permission or the truth of its contents.
The Python class tutorial and dataclass reference describe the mechanisms used here.
Reconstruct the instance's behaviour
Try these with the explanation closed:
- In
chapter.label(), where does the method'sselfvalue come from? - Why can a list written directly in a class body be shared by several instances?
- Which important method did
@dataclasssave us from writing explicitly? - Why can the final
appendsucceed despitefrozen=True? - Would a
Chapterdataclass necessarily rejectlesson_count="seven"? State what you would test.
Check after your attempt
The instance before the dot is supplied as self. A class-body list is created on the class rather than independently inside each instance's initialiser. A dataclass normally generates __init__ among other methods. Frozen prevents ordinary field reassignment, not all mutations of contained objects. A normal dataclass does not enforce its type annotations, so test the bad value instead of assuming it will be rejected.
Ask the AI to explain one class in an authorised solution in terms of the data each instance holds and the methods that can change it. Then continue to types and validation, where we separate an expected shape from an enforced boundary.