Python 装饰器 @
函数装饰器/@语法/functools.wraps/带参数装饰器 · 难度:入门 · +20XP
Python 装饰器 —— 给函数加功能不修改原代码
装饰器(Decorator)让你在不修改原函数代码的情况下给函数添加新功能——日志记录、性能计时、权限检查。它是Python中实现AOP的方式。
基本用法
import time
def timer(func):
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
print(f'{func.__name__} 耗时: {time.time()-start:.4f}s')
return result
return wrapper
@timer
def say_hello(name):
print(f'Hello, {name}')
time.sleep(1)
动手练习
- 基础练习:写一个装饰器,在函数执行前后打印开始和结束日志。
- 进阶应用:写一个带参数的装饰器——可以指定重试次数。
- 项目实战:给你的API调用函数加上重试装饰器。