Intermediate 8 min

Classes, instances, and dataclasses

A class gives related data and behavior a shared structure.

How it works

A class definition describes which fields every Book instance has. The instances each hold their own values, so a book with 120 pages can coexist with one with 80. Use a dataclass when the object mainly carries named fields. Write a regular method when the book needs to enforce a rule.

Walk through an example

A Book instance can hold its own title and page count. A dataclass can generate routine initialization and representation from declared fields.

What to watch for

A mutable default can accidentally be shared between instances. Use field(default_factory=list) when each instance should start with a fresh list.

Code example

from dataclasses import dataclass

@dataclass
class Book:
    title: str
    pages: int

book = Book("A", 120)
print(book.pages)

Check your understanding

Which object changes when you set the first book’s pages to 121?

See the example and explanation
Worked example
Given Book("A", 120) and Book("B", 80)
Answer Only Book A.

Each instance stores its own pages field. Assigning through the first object leaves the second untouched.

Open practice problem
Next lessonType hints and data contracts