Python · Advanced level

Advanced level · Module 1: Object-Oriented Programming in Python · Lesson 3 of 4

Dataclasses and Special Methods

Write concise data-holding classes and make objects print and compare naturally.

In this lesson you will

  • Use @dataclass with type hints
  • Implement __repr__ and ordering

Key concepts

@dataclasstype hints__repr__field defaults

The lesson

Many classes mainly hold data. The @dataclass decorator writes __init__, a readable __repr__ and equality checks for you, so a Product with name, price and stock takes three lines.

Special methods (with double underscores) let objects work with Python's built-in operations: __str__ controls how print shows the object, __lt__ allows sorting, __len__ allows len(). @dataclass(order=True) generates the comparison methods.

Dataclasses keep code short and clear, which makes the business rules easier to see.

Step by step

  1. Rewrite Product as a dataclass.
  2. Print a product and compare the output with the old class.
  3. Add order=True and sort a list of products.
  4. Add a __str__ method for receipt-style output.

Practice activity

Rewrite Product as a dataclass and sort a list of products by price using the dataclass ordering option.

Expected result: Products print readably and sort by price.

Check your understanding

  1. Name two methods @dataclass writes for you.

    Show answer

    __init__ and __repr__ (also __eq__).

Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.