Editor

Refactor: Add Validation and Computed Fields

Advanced · Refactor · from Advanced Dataclasses: __post_init__, frozen, field(), slots, and Inheritance

From the lesson: Advanced Dataclasses: __post_init__, frozen, field(), slots, and Inheritance

You already know the basics of dataclasses - how to define fields, get automatic __init__ and __repr__, and set default values. Now it's time to unlock the advanced features.

Read the lesson

Refactor this basic Product dataclass to add: (1) a __post_init__ that raises ValueError with 'Price must be positive' if price <= 0, (2) a computed field discounted_price (not in __init__) calculated as round(price * (1 - discount), 2). Create Product('Widget', 19.99, 0.15) and print its discounted_price.

from dataclasses import dataclass, field
@dataclass
class Product:
name: str
price: float
discount: float = 0.0
p = Product('Widget', 19.99, 0.15)
print(p.price)

More Advanced Dataclass exercises

All Python exercises · 50 practice problems · Object-Oriented Programming quiz