Python · Chapter 11 of 21
Python classes: attributes, properties, methods and dataclasses
15 min study · Examples checked with Python 3.14 and 3.15 ·
So far, data has lived in lists and dictionaries, and the rules about that data have lived in separate functions. A class puts the two together: it defines a new type whose objects carry their own data (attributes) and their own operations (methods), and can refuse to enter an invalid state. This chapter models courses and lessons, first with a hand-written class and then with dataclasses, which remove most of the boilerplate.
Define a class and create objects
class Course:
level = "beginner" # class attribute: shared by all courses
def __init__(self, title: str, seats: int):
if seats <= 0:
raise ValueError("seats must be positive")
self.title = title # instance attributes: one set per object
self.seats = seats
self.learners: list[str] = []
def enrol(self, name: str) -> None:
if len(self.learners) >= self.seats:
raise ValueError(f"{self.title} is full")
self.learners.append(name)
def __str__(self) -> str:
return f"{self.title} ({len(self.learners)}/{self.seats})"
python = Course("Python", 2)
django = Course("Django", 10)
python.enrol("Ada")
print(python, "|", django) # Python (1/2) | Django (0/10)
print(django.learners) # []
Calling Course("Python", 2) creates a new object and passes it, with the arguments, to __init__, whose job is to initialize it. self is that object; Python passes it automatically to every method, so python.enrol("Ada") is really Course.enrol(python, "Ada"). Attributes assigned to self belong to one object. The list is created inside __init__, so each course gets its own; a list written in the class body would be shared by every course, the same trap as a mutable default argument.
level is a class attribute, shared by all instances until one of them assigns its own. python.level = "advanced" creates an instance attribute on python only, which then hides the class value for that one object.
Printable objects: str and repr
Methods named with two _ characters on each side, such as __init__ and __str__, are called “dunder” methods; they let your class plug into Python’s built-in behaviour. __str__ is used by print and str() and should read well for users. __repr__ is what you see in the shell, inside printed lists and in the debugger, and should help a developer identify the object, ideally looking like the code that recreates it: Lesson('Loops', 15). If you define only __repr__, print uses it too. Without either, you get something like <__main__.Lesson object at 0x7f...>, which tells you nothing. Dataclasses, later in this chapter, write a good __repr__ for you.
Validate with properties
Python has no private attributes. A name starting with _, such as _minutes, is a convention meaning “internal, don’t touch from outside”. When an attribute needs rules, a property keeps the simple obj.attr syntax while running code on every read or write:
class Lesson:
def __init__(self, title: str, minutes: int):
self.title = title
self.minutes = minutes # goes through the setter below
@property
def minutes(self) -> int:
return self._minutes
@minutes.setter
def minutes(self, value: int) -> None:
if value <= 0:
raise ValueError("minutes must be positive")
self._minutes = value
@property
def hours(self) -> float: # computed, read-only
return round(self._minutes / 60, 2)
lesson = Lesson("Classes", 45)
lesson.minutes = 90
print(lesson.minutes, lesson.hours) # 90 1.5
# lesson.minutes = 0 would raise ValueError: minutes must be positive
Because __init__ assigns through the property, the same rule applies at creation and on every later change. hours has no setter, so it is read-only and always consistent with minutes. Don’t write getters and setters for attributes that need no rules; a plain attribute can be turned into a property later without changing any calling code. Two leading _ characters (self.__secret) trigger name mangling, which avoids clashes in subclasses but is not a security barrier.
Class methods and static methods
A regular method works on one instance. A @classmethod receives the class itself as cls and is typically used as an alternative constructor. A @staticmethod receives nothing automatically; it is a plain function that lives in the class’s namespace.
class Slug:
def __init__(self, value: str):
self.value = value
@classmethod
def from_title(cls, title: str) -> "Slug":
return cls("-".join(title.casefold().split()))
@staticmethod
def is_valid(value: str) -> bool:
return bool(value) and " " not in value
print(Slug.from_title("Python Basics").value) # python-basics
Using cls(...) rather than Slug(...) means a subclass calling from_title gets an instance of the subclass. Static methods are optional; a module-level function is just as good when the grouping adds nothing.
Dataclasses: less code for data-holding classes
Many classes mostly hold data. The dataclasses module writes __init__, __repr__ and __eq__ for you from annotated fields:
from dataclasses import dataclass, field
@dataclass
class Learner:
name: str
completed: int = 0
courses: list[str] = field(default_factory=list)
def __post_init__(self) -> None:
if self.completed < 0:
raise ValueError("completed cannot be negative")
ada = Learner("Ada")
ada.courses.append("Python")
print(ada) # Learner(name='Ada', completed=0, courses=['Python'])
print(Learner("Ada", 2) == Learner("Ada", 2)) # True
@dataclass(frozen=True, order=True)
class Version:
major: int
minor: int
print(sorted([Version(3, 15), Version(3, 9)])) # [Version(major=3, minor=9), Version(major=3, minor=15)]
field(default_factory=list) gives every instance a fresh list. __post_init__ runs after the generated __init__ and is the place for validation. frozen=True makes instances read-only and hashable, so they can be dictionary keys; order=True compares instances field by field, which is why 3.9 sorts before 3.15 here, as numbers and not as text. Type annotations in a dataclass are not checked at runtime: Learner("Ada", "lots") is accepted. When input comes from outside, validate it, or use a library such as Pydantic that converts and checks (the FastAPI track uses it).
Enums for fixed sets of values
When a value must be one of a few known options, such as a course status, an Enum is safer than bare strings, because a typo becomes an error instead of a silent new state:
from enum import Enum
class Status(Enum):
DRAFT = "draft"
PUBLISHED = "published"
ARCHIVED = "archived"
status = Status("published")
print(status, status.value, status is Status.PUBLISHED) # Status.PUBLISHED published True
Status("published") converts stored text back into a member and raises ValueError for unknown text. Members are singletons, so compare them with is.
Objects also need cleanup sometimes: closing a file, releasing a lock. Don’t rely on __del__ for that, since Python does not promise when it runs. Use a context manager and a with statement (chapter 14).
Practice
Write a StudyPlan dataclass with a learner name and a list of Lesson objects (use the property version of Lesson above). Add a total_minutes property and an add(lesson) method that refuses a lesson whose title is already in the plan.
Answer check: two plans created without arguments must not share their list, so use default_factory. total_minutes should be sum(l.minutes for l in self.lessons). Adding “Loops” twice should raise ValueError, and Lesson("Loops", 0) should fail before it ever reaches the plan, because the property validates it.
Summary
A class bundles data with the rules and operations for it. Set instance attributes in __init__, give objects a useful __repr__, protect rules with properties, use @classmethod for alternative constructors, reach for @dataclass when a class mainly holds data, and use Enum for fixed sets of values.