Lesson 38 of 41
Object-Oriented Python for Analysts: Classes, @dataclass & Encapsulation
Overview & Learning Objectives
As analytics projects evolve from scratchpad exploratory notebooks into reusable production tools, procedural code with scattered dictionaries and global variables becomes brittle. Object-Oriented Programming (OOP) enables analysts to bundle state (data tables, API credentials, configuration) and behavior (cleansing, aggregation, reporting) into structured classes. Modern Python’s `@dataclass` decorator drastically reduces boilerplate for data modeling.
- Define clean business domain models using Python’s modern `@dataclass` decorator with strict type hints.
- Implement encapsulation and read-only calculated attributes using the `@property` decorator.
- Construct a modular `DarkStoreAnalyzer` class that ingests raw data, computes business metrics, and outputs formatted summaries.
Industry Standard
Standard: Quantitative analytics libraries at Goldman Sachs and Two Sigma organize all algorithmic trading strategies into disciplined OOP class hierarchies inheriting from abstract base classes.
Real-World Example: ScoopCraft Dark-Store Analytics Object Architecture
ScoopCraft engineers a production `StorePerformance` class encapsulating sales, labor hours, and margin calculations.
| Class Component | Type | Encapsulated Logic | Business Value |
|---|---|---|---|
| StorePerformance | @dataclass | store_id, revenue, labor_cost, co_cost | Structured typed business entity |
| net_profit | @property | revenue - (labor_cost + co_cost) | Computed on demand without stale caching |
| profit_margin_pct | @property | (net_profit / revenue) * 100 | Enforces zero-division protection |
| is_underperforming | method | margin < target_threshold | Automated flag for executive intervention |
Syntax & Core Code Implementation
from dataclasses import dataclass
from typing import List
@dataclass
class DarkStoreOrder:
order_id: str
dark_store: str
items_count: int
subtotal: float
tip: float = 0.0
@property
def total_revenue(self) -> float:
"""Dynamically calculated total basket revenue."""
return round(self.subtotal + self.tip, 2)
def is_bulk_order(self, threshold: int = 5) -> bool:
"""Determines if the order requires priority packing."""
return self.items_count >= threshold
# Instantiating and using typed domain models
order = DarkStoreOrder('ORD-101', 'Koramangala', 6, 42.50, 4.00)
print(f"Order {order.order_id} Total: ${order.total_revenue} | Bulk: {order.is_bulk_order()}")
Parameters & Arguments Breakdown
@dataclass: Automatically generates __init__(), __repr__(), and __eq__() methods based on class type annotations.@property: Defines a getter method that can be accessed like a normal attribute without function call parentheses.typing.List / Optional: Explicit data contract annotations documenting expected variable types.
Step-by-Step Implementation
- Model Domain Entity: Decorate class with `@dataclass` and define fields with explicit type annotations.
- Expose Computed Attributes: Use `@property` for derived metrics so callers cannot manually overwrite calculated figures.
- Implement Analytic Methods: Add business validation and calculation methods directly to the entity class.
Common Mistakes & Limitations
- Using mutable default arguments (like `items: list = []`) in dataclasses; use `field(default_factory=list)` instead to avoid shared state across instances.
- Over-engineering simple one-off data scripts into massive class hierarchies before understanding domain requirements.
- Allowing external code to modify critical state directly without validation instead of using private attributes (`_variable`).
Keyboard Shortcuts (Jupyter & VS Code)
| Action | Windows | Mac |
|---|---|---|
| Go to Class / Method Definition in VS Code | F12 | F12 |
Pro Tips & Modern Best Practices
- Set `@dataclass(frozen=True)` to create immutable value objects that can be safely used as dictionary keys or stored in sets.
- Use `__post_init__()` inside a dataclass to validate business constraints immediately upon object creation (e.g. asserting price > 0).