Property Decorators (@property, @setter, @deleter)
1Concept
`@property` enables Pythonic getters and setters with validation logic without altering client API syntax (`obj.field` rather than `obj.get_field()`). It provides clean backward-compatible encapsulation.
2Architecture Diagram
Client access: acc.balance = 500 ---> Invokes @balance.setter ---> Validates (amount >= 0)
3Code Example
Python 3.12
class BankAccount:
def __init__(self, owner: str, initial_balance: float):
self.owner = owner
self._balance = initial_balance
@property
def balance(self) -> float:
return self._balance
@balance.setter
def balance(self, amount: float):
if amount < 0:
raise ValueError("Account balance cannot be negative!")
self._balance = amount
acc = BankAccount("Alice", 1500.0)
acc.balance += 250.0
print(f"Updated balance for {acc.owner}: ${acc.balance:.2f}")
try:
acc.balance = -50.0
except ValueError as e:
print(f"Validation Blocked: {e}")4Expected Output
Updated balance for Alice: $1750.00 Validation Blocked: Account balance cannot be negative!
5Key Takeaways
- ✓Properties allow adding validation logic without breaking existing code using attribute access.
- ✓Use leading underscore `_attr` to indicate private/internal attributes by convention.
- ✓Use `@property.deleter` to control resource cleanup when attributes are deleted via `del`.