Python - __post_init__ method in Dataclasses
Python tip:
You can use
__post_init__
on classes decorated withdataclass
to add custom logic on init.For example, to set a value of an attribute based on a different attribute's value:
from dataclasses import dataclass, field @dataclass class Order: net: float vat: float total: float = field(init=False) def __post_init__(self): self.total = self.net + self.vat order = Order(net=100.00, vat=22.00) print(order) # => Order(net=100.0, vat=22.0, total=122.0)