import functools
import tracemalloc
def cache_decorator(func):
cache = {}
@functools.wraps(func)
def wrapper(*args, **kwargs):
key = (args, tuple(sorted(kwargs.items())))
if key in cache:
return cache[key]
result = func(*args, **kwargs)
cache[key] = result
return result
return wrapper
def error_handling_decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except ZeroDivisionError:
return "捕获到除零错误,返回特定值"
return wrapper
def performance_monitor_decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
tracemalloc.start()
result = func(*args, **kwargs)
current, peak = tracemalloc.get_traced_memory()
tracemalloc.stop()
print(f"函数 {func.__name__} 执行时占用的内存峰值: {peak} 字节")
return result
return wrapper
# 假设存在复杂函数
def complex_function(*args, **kwargs):
"""这是一个复杂函数的文档字符串"""
# 这里是复杂的循环和条件判断逻辑示例
total = 0
for arg in args:
if isinstance(arg, int):
total += arg
for value in kwargs.values():
if isinstance(value, int):
total += value
return total
# 以正确顺序嵌套装饰器
complex_function = cache_decorator(error_handling_decorator(performance_monitor_decorator(complex_function)))
解释
cache_decorator
:
- 使用字典
cache
来存储函数的计算结果。
functools.wraps
用于保留原函数的元数据,如函数名和文档字符串。
- 将位置参数
args
和关键字参数kwargs
组成一个唯一的键key
,如果key
在cache
中,直接返回缓存的结果;否则,调用原函数计算结果并缓存。
error_handling_decorator
:
- 使用
try - except
块捕获ZeroDivisionError
异常。
functools.wraps
保留原函数元数据。
- 如果捕获到
ZeroDivisionError
,返回特定值;否则,正常返回原函数的执行结果。
performance_monitor_decorator
:
- 使用
tracemalloc
模块来获取函数执行时占用的内存峰值。
functools.wraps
保留原函数元数据。
- 启动
tracemalloc
,调用原函数,获取当前内存和峰值内存,停止tracemalloc
,并打印内存峰值,最后返回原函数执行结果。
- 装饰器嵌套顺序:
- 这里将
cache_decorator
放在最外层,error_handling_decorator
在中间,performance_monitor_decorator
在最内层。这样的顺序确保了先进行性能监控,然后处理异常,最后缓存结果,且各装饰器功能互不干扰。同时,functools.wraps
保证了原函数的元数据在装饰后依然保留。