Python Decorators 入门 一个 decorator 本质上是一个接受函数并返回函数的高阶函数。 基础语法: @my_decorator def hello(): print('hello world') 等价于:hello = my_decorator(hello) 实用例子 - 计时器: import time def timer(func): def wrapper(*args, **kwargs): start = time.time() result = func(*args, **kwargs) print(f'耗时 {time.time()-start:.2f}s') return result return wrapper Decorator 是 Python 最优雅的特性之一,广泛用于日志、权限检查、缓存等场景。