
# Python 装饰器实战从入门到精通## 什么是装饰器装饰器Decorator是 Python 中一种强大的工具它允许你在不修改原函数代码的情况下动态地给函数添加功能。简单来说装饰器就是一个包装器它包裹住你的函数在函数执行前后添加额外的逻辑。## 基础语法装饰器的基本语法使用 符号pythondef my_decorator(func):def wrapper():print(函数执行前)func()print(函数执行后)return wrappermy_decoratordef say_hello():print(Hello!)say_hello()# 输出:# 函数执行前# Hello!# 函数执行后## 实用场景一日志记录pythonimport functoolsfrom datetime import datetimedef log_decorator(func):functools.wraps(func)def wrapper(*args, **kwargs):print(f[{datetime.now()}] 调用函数{func.__name__})result func(*args, **kwargs)print(f[{datetime.now()}] 函数执行完成)return resultreturn wrapperlog_decoratordef add(a, b):return a badd(3, 5)## 实用场景二性能计时pythonimport timedef timing_decorator(func):functools.wraps(func)def wrapper(*args, **kwargs):start time.time()result func(*args, **kwargs)end time.time()print(f{func.__name__} 执行耗时{end - start:.4f}秒)return resultreturn wrappertiming_decoratordef slow_function():time.sleep(2)print(任务完成)slow_function()## 实用场景三权限验证pythondef require_auth(func):functools.wraps(func)def wrapper(user, *args, **kwargs):if not user.is_authenticated:raise PermissionError(用户未登录)return func(user, *args, **kwargs)return wrapperrequire_authdef delete_account(user):print(删除账户)## 带参数的装饰器pythondef repeat(times):def decorator(func):functools.wraps(func)def wrapper(*args, **kwargs):for _ in range(times):result func(*args, **kwargs)return resultreturn wrapperreturn decoratorrepeat(3)def greet(name):print(fHello, {name}!)greet(World)## 多个装饰器叠加pythonlog_decoratortiming_decoratordef process_data():time.sleep(1)print(数据处理完成)process_data()## 总结装饰器是 Python 中的高级特性掌握它可以让你写出更优雅、更模块化的代码。常见的应用场景包括- 日志记录- 性能监控- 权限验证- 缓存机制- 事务处理记住使用 functools.wraps 来保留原函数的元信息这是一个好的实践习惯。