摘要:装饰器(Decorator)是 Python 中一种强大的语法特性,它允许在不修改原函数代码的前提下,动态地扩展或修改函数的行为。装饰器的核心思想是函数可以作为参数传递和返回值,利用闭包特性实现功能的增强。
装饰器(Decorator)是 Python 中一种强大的语法特性,它允许在不修改原函数代码的前提下,动态地扩展或修改函数的行为。装饰器的核心思想是函数可以作为参数传递和返回值,利用闭包特性实现功能的增强。
核心概念
函数是一等公民函数可以像变量一样被赋值、传递或作为返回值。闭包(Closure)
内部函数可以捕获并保存外部函数的变量,即使外部函数已经执行完毕。语法糖 @
@decorator 是 func = decorator(func) 的简写形式。
最简单的装饰器示例
python
def my_decorator(func):
def wrapper:
print("Something is happening before the function is called.")
func
print("Something is happening after the function is called.")
return wrapper
@my_decorator
def say_hello:
print("Hello!")
say_hello
输出:
Something is happening before the function is called.
Hello!
Something is happening after the function is called.
装饰器执行流程
@my_decorator 等价于 say_hello = my_decorator(say_hello)实际调用的是 wrapper 函数,原函数被包裹在其中处理带参数的函数
使用 *args 和 **kwargs 接受任意参数:
python
def decorator(func):
def wrapper(*args, **kwargs):
print("Decorator work")
return func(*args, **kwargs)
return wrapper
保留原函数信息
使用 functools.wraps 保持函数元数据:
python
from functools import wraps
def decorator(func):
@wraps(func) # 保留原函数名称、文档等属性
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
return wrapper
带参数的装饰器
需要三层嵌套函数:
python
def repeat(num_times):
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
for _ in range(num_times):
result = func(*args, **kwargs)
return result
return wrapper
return decorator
@repeat(num_times=3)
def greet(name):
print(f"Hello {name}")
greet("Alice")
类装饰器
通过实现 __call__ 方法让类成为装饰器:
python
class CountCalls:
def __init__(self, func):
self.func = func
self.calls = 0
def __call__(self, *args, **kwargs):
self.calls += 1
print(f"Call {self.calls} of {self.func.__name__}")
return self.func(*args, **kwargs)
@CountCalls
def example:
print("Hello")
example # 输出调用次数
常见应用场景
日志记录执行时间计算权限验证缓存(如 functools.lru_cache)错误重试机制路由注册(Web框架常用)嵌套装饰器执行顺序
装饰器按照从下往上的顺序应用:
python
@decorator1
@decorator2
def func:
pass
等价于 func = decorator1(decorator2(func))
通过装饰器,Python 实现了优雅的 AOP(面向切面编程)范式,将核心逻辑与辅助功能解耦,极大提升了代码的可维护性和复用性。理解装饰器是掌握 Python 高级编程的重要一步。
来源:老客数据一点号