Skip to content
Guest
Learn Python · Course Syllabus Show lessons
Object-Oriented Python · 8 min read · Beginner

Classes & @dataclass

Model structured domain objects cleanly using Python's @dataclass decorator, type annotations, and instance methods.

What you'll learn

  • Use @dataclass to auto-generate __init__, __repr__, and equality comparisons
  • Add behavior with clean instance methods receiving self

Writing repetitive __init__ and __repr__ boilerplate is a thing of the past. Python’s standard-library @dataclass decorator generates them automatically from typed fields!

Fill-in-the-Blank Exercise

Define a Python Dataclass

Decorate Course with @dataclass and reference self inside its method.

from dataclasses import dataclass

@
class Course:
  title: str
  lessons: int

  def label():
      return f"{self.title} ({self.lessons})"

Try It Yourself

PythonClean Python @dataclass
Python Output (WebAssembly / Pyodide)

Click Run Python to execute real Python 3 right in your browser.

Check Your Understanding

Score: 0 / 1

1. What does the @dataclass decorator automatically generate for a Python class?

Study Workspace

Finished this lesson?

Your progress is saved locally in your browser, no account needed.

Search courses, lessons, and references

Type to search across all courses, lessons, and quick references.

Press Esc to close Powered by Pagefind