Work with data · 14 min

Classes and data classes

Keep related values and behavior together.

A class defines a type. Calling the class makes an instance. Each instance can hold its own attributes. Inside a method, self refers to the instance receiving the call.

A data class is convenient for records. The @dataclass decorator generates an initializer from annotated fields, along with a readable representation and equality by field values. Methods still work like they do on a regular class.

Follow the example

The data class defines the fields each book holds.

Try it yourself

Create two Book instances with 120 and 95 pages. Store them in a list and print their combined page count.

Target output

215
Show a hint

Use sum(book.pages for book in books) to add the pages.

Output

Ready

Run your code to see the output here.

The first run downloads Python. Code runs in your browser. Progress and drafts are stored on this device.

Show one solution
from dataclasses import dataclass

@dataclass
class Book:
    title: str
    pages: int

books = [Book("Coast", 120), Book("Forest", 95)]
print(sum(book.pages for book in books))