A class defines a type of object, combining its attributes and methods. It also acts as a factory for creating instances that represent a domain concept more explicitly than a generic data structure. section 10.1 section 10.5
Build a class by working through these implementation points:
- Declare the class with class and specify any inherited classes in parentheses. section 10.6
- Initialize instance attributes in __init__; Python passes the new instance as the first argument, conventionally named self. section 10.6
- Define methods that operate on instance state through self, remembering that Python does not enforce parameter types. section 10.6
- Use composition when one object contains other objects, and inheritance when a class extends behavior from another class. section 10.12 section 10.3
- Use @dataclass when attribute assignment and standard representations would otherwise create repetitive boilerplate; annotated fields are required there. section 10.12
Modeling scores as an object
A ScoreList stores scores and exposes the domain operation directly: scores = ScoreList([85, 95, 98, 87, 80, 92]); scores.average(). The calculation remains an arithmetic mean, but ownership of the data and behavior becomes explicit. section 10.1
class ScoreList():
def __init__(self, scores):
self.scores = scores
def average(self):
return sum(self.scores) / len(self.scores)
scores = ScoreList([85, 95, 98, 87, 80, 92])
print(f'The final score is {scores.average()}.')
Inspect the complete ScoreList implementation, including __init__, self.scores, average, instance creation, and method invocation. section 10.1
Practice extension
Create Book and Shelf classes. Add books, calculate total price, test whether a title exists, and reject books whose combined widths exceed the shelf’s capacity. section 10.12




















