Python Foundations · Objects & reliability
Classes & dataclasses
Bundle data and behavior. Model a Trade with a dataclass and give it methods.
Step 1 of 4 · 1. A class is a blueprint15 min read ·
1. A class is a blueprint
from dataclasses import dataclass
from decimal import Decimal
@dataclass(frozen=True)
class Trade:
id: str
qty: int
px: Decimal
def notional(self) -> Decimal:
return self.qty * self.px
t = Trade("T1", 100, Decimal("99.50"))
t.notional() # Decimal('9950.00')@dataclass writes __init__, __repr__ and __eq__ for you. frozen=True makes instances immutable, which is great for records that must not change after booking.
Class
Trade (blueprint)
Instance
Trade('T1',100,99.50)
Attribute
t.qty
Method
t.notional()
Key idea
Recon tie-in: two frozen Trade objects compare with == field by field, so ours == theirs is a one-line match check.Next: Practice