Attribute Decorator Patterns
Understanding Attribute Decorators
Attribute decorators in Python are specialized decorators that modify or control attribute access, creation, and manipulation within classes.
Property Decorator
The @property
decorator allows controlled access to class attributes:
class Temperature:
def __init__(self, celsius):
self._celsius = celsius
@property
def fahrenheit(self):
return (self._celsius * 9/5) + 32
@property
def celsius(self):
return self._celsius
@celsius.setter
def celsius(self, value):
if value < -273.15:
raise ValueError("Temperature below absolute zero is impossible")
self._celsius = value
Decorator Types for Attributes
Decorator |
Purpose |
Use Case |
@property |
Create managed attributes |
Controlled attribute access |
@classmethod |
Define methods operating on class |
Alternative constructors |
@staticmethod |
Create method independent of instance |
Utility functions |
Attribute Validation Decorator
def validate_type(expected_type):
def decorator(func):
def wrapper(self, value):
if not isinstance(value, expected_type):
raise TypeError(f"Expected {expected_type.__name__}")
return func(self, value)
return wrapper
return decorator
class User:
def __init__(self):
self._age = None
@validate_type(int)
def set_age(self, age):
self._age = age
Attribute Decorator Flow
graph TD
A[Attribute Access] --> B{Decorator Applied?}
B -->|Yes| C[Decorator Processing]
B -->|No| D[Direct Access]
C --> E[Validation/Transformation]
E --> F[Final Attribute Value]
Advanced Attribute Descriptor
class PositiveNumber:
def __init__(self, name):
self.name = name
def __get__(self, instance, owner):
return instance.__dict__.get(self.name, None)
def __set__(self, instance, value):
if value <= 0:
raise ValueError("Must be positive")
instance.__dict__[self.name] = value
class Product:
price = PositiveNumber('price')
quantity = PositiveNumber('quantity')
def __init__(self, name, price, quantity):
self.name = name
self.price = price
self.quantity = quantity
Key Patterns
- Attribute Access Control
- Type Validation
- Computed Properties
- Lazy Loading
- Data Transformation
Best Practices
- Use decorators for clean, reusable attribute logic
- Maintain clear separation of concerns
- Avoid overly complex decorator implementations
- Consider performance implications
Explore these patterns in your LabEx Python projects to write more elegant and robust code.