实际示例
现实世界中的装饰器链场景
装饰器链不仅仅是一个理论概念,而是一种强大的技术,在软件开发中有许多实际应用。
1. 认证和日志记录装饰器
def require_login(func):
def wrapper(*args, **kwargs):
if not is_user_authenticated():
raise PermissionError("需要登录")
return func(*args, **kwargs)
return wrapper
def log_performance(func):
def wrapper(*args, **kwargs):
start_time = time.time()
result = func(*args, **kwargs)
end_time = time.time()
print(f"{func.__name__} 执行耗时 {end_time - start_time} 秒")
return result
return wrapper
@require_login
@log_performance
def sensitive_operation():
## 复杂的数据库或 API 操作
pass
2. 数据验证和转换
def validate_input(validator):
def decorator(func):
def wrapper(*args, **kwargs):
if not validator(*args, **kwargs):
raise ValueError("无效输入")
return func(*args, **kwargs)
return wrapper
return decorator
def convert_to_type(target_type):
def decorator(func):
def wrapper(*args, **kwargs):
result = func(*args, **kwargs)
return target_type(result)
return wrapper
return decorator
@convert_to_type(int)
@validate_input(lambda x: x > 0)
def process_number(value):
return value * 2
装饰器链工作流程
graph TD
A[输入数据] --> B[验证装饰器]
B --> C[类型转换装饰器]
C --> D[核心函数]
D --> E[最终结果]
3. 缓存和重试机制
def retry(max_attempts=3):
def decorator(func):
def wrapper(*args, **kwargs):
attempts = 0
while attempts < max_attempts:
try:
return func(*args, **kwargs)
except Exception as e:
attempts += 1
if attempts == max_attempts:
raise e
return wrapper
return decorator
def cache_result(func):
cache = {}
def wrapper(*args):
if args not in cache:
cache[args] = func(*args)
return cache[args]
return wrapper
@retry(max_attempts=3)
@cache_result
def fetch_data(url):
## 模拟网络请求
pass
装饰器链最佳实践
实践 |
描述 |
建议 |
顺序很重要 |
从特定到一般应用装饰器 |
自下而上的方法 |
性能 |
最小化装饰器复杂度 |
避免繁重的计算 |
可读性 |
保持装饰器专注 |
单一职责原则 |
4. LabEx 环境中的计时和性能分析
import time
import functools
def timeit(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
start = time.perf_counter()
result = func(*args, **kwargs)
end = time.perf_counter()
print(f"{func.__name__} 耗时 {end - start:.4f} 秒")
return result
return wrapper
def profile_memory(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
import tracemalloc
tracemalloc.start()
result = func(*args, **kwargs)
current, peak = tracemalloc.get_traced_memory()
print(f"{func.__name__} 内存使用情况:当前 {current},峰值 {peak}")
tracemalloc.stop()
return result
return wrapper
@timeit
@profile_memory
def complex_computation():
## 计算任务
pass
要点总结
- 装饰器链能够实现复杂的行为修改
- 对于日志记录、认证等横切关注点很有用
- 支持模块化和可重用的代码设计
- 适用于各个领域:网页开发、数据处理
- 在 LabEx 等 Python 编程环境中是一项强大的技术