3. Modern OOP, Dataclasses & Context Managers
Python Data Model: Dunder Methods & @property
Make custom Python classes feel like built-in types using dunder methods (__repr__, __str__, __len__, __getitem__, __iter__) and validate attributes cleanly with @property.
- Distinguish developer-focused __repr__ from user-facing __str__
- Support len(), indexing, equality, and iteration on custom classes with dunder methods
- Expose computed attributes and validated setters safely via @property
Why does len(my_list), playlist[0], and for track in playlist: work so smoothly in Python? Because Python's Data Model routes built-in functions and operators straight to special double-underscore ("dunder") methods on your class.
Why It Matters: Before vs After
Coming from Java or C#, developers often write awkward .get_size() and .set_price() methods—forcing callers out of idiomatic Python:
# Before: noisy Java-style getter/setter & helper methods
cart.get_item_count()
cart.get_item(0)
product.set_price(25.0)
# After: native Python protocols via dunder methods & @property
len(cart) # Calls cart.__len__()
cart[0] # Calls cart.__getitem__(0)
product.price = 25.0 # Calls @price.setter cleanly!Best of all: you can start with a plain public attribute (self.price = price) and upgrade it to a validated @property later without changing a single line of caller code!
1. __repr__ vs __str__ (And Operator Dunders)
__repr__(self)is for developers and debugging: aim for an unambiguous string that looks like Python code (Money(amount=19.99, currency='USD')). Used in lists, REPLs, and tracebacks.__str__(self)is for end users (called byprint(obj)andf"{obj}"). If__str__isn't defined, Python falls back to__repr__—so always implement__repr__first!
class Money:
def __init__(self, amount: float, currency: str = "USD"):
self.amount = round(amount, 2)
self.currency = currency
def __repr__(self) -> str:
return f"Money(amount={self.amount!r}, currency={self.currency!r})"
def __str__(self) -> str:
return f"{self.amount:.2f} {self.currency}"
def __add__(self, other: object) -> "Money":
if not isinstance(other, Money):
return NotImplemented
if self.currency != other.currency:
raise ValueError("Cannot add different currencies")
return Money(self.amount + other.amount, self.currency)(Notice return NotImplemented when other is an unknown type—that lets Python try other.__radd__(self) before raising TypeError, instead of crashing immediately!)
2. Container Dunder Methods (__len__, __getitem__, __iter__)
Implement just three dunder methods and your custom class behaves like a native Python sequence:
class Deck:
def __init__(self, cards: list[str]):
self._cards = list(cards)
def __len__(self) -> int:
return len(self._cards)
def __getitem__(self, index: int):
return self._cards[index]
def __iter__(self):
return iter(self._cards)| Python Syntax | Dunder Method Called | What It Enables |
|---|---|---|
len(deck) | deck.__len__() | Sizing and automatic truthiness (bool(deck) is False if length is 0) |
deck[0] / deck[1:3] | deck.__getitem__(idx) | Indexing and slicing |
for c in deck: | deck.__iter__() | Iteration, list(deck), and "Ace" in deck membership checks |
a + b | a.__add__(b) | Custom operator overloading (Money, Vector, Path / "file") |
3. Clean Validation & Computed Fields with @property
When you decorate a method with @property, Python wraps it in a descriptor so reading product.price runs the getter function automatically, and assigning product.price = 19.99 runs @price.setter:
class Product:
def __init__(self, name: str, price: float):
self.name = name
self.price = price # Calls @price.setter automatically!
@property
def price(self) -> float:
return self._price
@price.setter
def price(self, value: float) -> None:
if value < 0:
raise ValueError("Price cannot be negative")
self._price = round(float(value), 2)
@property
def price_with_tax(self) -> float:
"""Read-only computed property (no setter defined)."""
return round(self._price * 1.1, 2)Notice why self.price = price inside __init__ is so powerful: even initial construction passes through your validation rules!
Inside @property def price(self):, store the internal value in self._price (with a leading underscore), never self.price! Writing self.price = value inside @price.setter triggers the setter recursively until Python crashes with RecursionError.
Try It Yourself in the Playground
Click “Run Code” to execute this snippet right in your browser.
Mini-Challenge: Add a __len__ method to a Playlist class holding self._songs: list[str] and a read-only @property def is_empty(self) -> bool: returning len(self._songs) == 0.
Quick Checkpoints
If a class defines __repr__ but does NOT define __str__, what happens when you call print(obj)?
Why do @property getters and setters usually read/write self._name instead of self.name?