Property Decorators
Introduction to Property Decorators
Property decorators provide a clean and pythonic way to define and manage object attributes with custom behavior, enabling more sophisticated attribute handling.
Core Property Decorators
@property Decorator
class User:
def __init__(self, first_name, last_name):
self._first_name = first_name
self._last_name = last_name
@property
def full_name(self):
"""Generate full name dynamically"""
return f"{self._first_name} {self._last_name}"
Decorator Types
Decorator |
Purpose |
Behavior |
@property |
Getter |
Read-only attribute |
@.setter |
Setter |
Modify attribute |
@.deleter |
Deleter |
Remove/reset attribute |
Complete Property Decorator Example
class BankAccount:
def __init__(self, balance=0):
self._balance = balance
@property
def balance(self):
"""Read-only balance"""
return self._balance
@balance.setter
def balance(self, value):
"""Validate and set balance"""
if value < 0:
raise ValueError("Balance cannot be negative")
self._balance = value
@balance.deleter
def balance(self):
"""Reset balance"""
self._balance = 0
Property Decorator Workflow
graph TD
A[Decorator Applied] --> B{Property Type}
B -->|Getter| C[Return Value]
B -->|Setter| D[Validate Input]
B -->|Deleter| E[Reset/Remove]
Advanced Decorator Techniques
Custom Property Decorator
def validate_positive(func):
def wrapper(self, value):
if value < 0:
raise ValueError("Value must be positive")
return func(self, value)
return wrapper
class Product:
def __init__(self, price):
self._price = price
@property
def price(self):
return self._price
@price.setter
@validate_positive
def price(self, value):
self._price = value
Use Cases
- Data validation
- Computed attributes
- Controlled attribute access
- Lazy loading
- Type conversion
- Property decorators have slight overhead
- Use for complex attribute management
- Avoid heavy computations in decorators
Best Practices
- Keep decorator logic simple
- Use type hints
- Handle potential exceptions
- Maintain clear, readable code
LabEx Recommendation
At LabEx, we recommend mastering property decorators as a key technique for creating robust, flexible Python classes with intelligent attribute management.