Computed Field with __post_init__
Intermediate · Write the code · 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 lessonCreate a dataclass BMI with fields weight_kg (float) and height_m (float). Add a computed field bmi (float, not in __init__) that is calculated in __post_init__ as weight_kg / (height_m ** 2). Round the bmi to 1 decimal place using round(). Create a BMI(70, 1.75) and print the bmi value.
from dataclasses import dataclass, field
# Create BMI dataclass with computed field
# Create instance and print bmi
More Advanced Dataclass exercises
- Validate with __post_init__Beginner
- Safe List Default with field()Beginner
- Predict the Output: Frozen DataclassIntermediate
- Dataclass InheritanceAdvanced
- Refactor: Add Validation and Computed FieldsAdvanced
All Python exercises · 50 practice problems · Object-Oriented Programming quiz