1. 装饰器基础概念与核心价值
装饰器(Decorator)是Python中一种强大的语法特性,它允许在不修改原函数代码的情况下,为函数或类添加额外的功能。这种设计模式在Python社区被广泛称为"元编程"的经典实践。
装饰器的本质是一个高阶函数,它接收一个函数作为参数,并返回一个新的函数。这个特性源于Python将函数视为一等对象的特性——函数可以像普通变量一样被传递和返回。在实际开发中,装饰器常用于以下场景:
- 日志记录
- 性能测试(如计算函数执行时间)
- 权限校验
- 缓存处理
- 输入合法性检查
重要提示:装饰器语法中的@符号实际上是Python提供的语法糖,它简化了手动包装函数的操作。理解这一点对掌握装饰器的工作原理至关重要。
需要模型API调用? 免费领10W Token,多模型网关一键接入 Claude、DeepSeek 等主流模型。
2. 装饰器工作原理深度解析
2.1 函数装饰器的实现机制
让我们从一个最简单的装饰器示例开始:
python复制def simple_decorator(func):
def wrapper():
print("Before function execution")
func()
print("After function execution")
return wrapper
@simple_decorator
def say_hello():
print("Hello!")
say_hello()
这段代码的执行流程是:
- 当解释器遇到@simple_decorator时,会立即执行simple_decorator(say_hello)
- simple_decorator返回wrapper函数替代原say_hello
- 调用say_hello()实际执行的是wrapper()
2.2 处理带参数的函数
实际应用中,被装饰的函数通常带有参数。这时需要在wrapper函数中接收并传递这些参数:
python复制def param_decorator(func):
def wrapper(*args, **kwargs):
print(f"Calling {func.__name__} with args: {args}, kwargs: {kwargs}")
return func(*args, **kwargs)
return wrapper
这里的*args和**kwargs确保了装饰器可以处理任意参数的函数调用,这是编写通用装饰器的关键技巧。
3. 高级装饰器模式与实践
3.1 带参数的装饰器
有时我们需要装饰器本身也能接收参数,这需要再嵌套一层函数:
python复制def repeat(num_times):
def decorator(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")
