Lesson 3 of 4Module 2 · 0% of course
Explore › CS, Python & AI Engineering › Python Foundations › Objects & reliability
Python Foundations · Objects & reliability

Classes & dataclasses

Bundle data and behavior. Model a Trade with a dataclass and give it methods.

15 min · 4 steps · videoJump to quiz ↓
Python's Class Development Toolkit Next Day Video · 46 min
Open in YouTube
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
‹ PrevNext ›