Python装饰器:优雅的函数增强术
在Python中,装饰器(Decorator)是一种强大的语法特性,它允许我们在不修改原函数代码的情况下,为其添加新功能。这种“元编程”能力使代码更加模块化和可复用。
装饰器基础
装饰器本质上是一个函数,它接受一个函数作为参数,并返回一个新函数。最常见的用途包括日志记录、性能测试、权限校验等。
def simple_decorator(func):
def wrapper():
print("函数执行前")
func()
print("函数执行后")
return wrapper
@simple_decorator
def say_hello():
print("Hello, World!")
say_hello()
带参数的装饰器
实际开发中,我们常常需要装饰器能够接受参数:
import time
def timer_decorator(repeat=1):
def decorator(func):
def wrapper(*args, **kwargs):
total_time = 0
for _ in range(repeat):
start = time.time()
result = func(*args, **kwargs)
total_time += time.time() - start
print(f"平均执行时间: {total_time/repeat:.4f}秒")
return result
return wrapper
return decorator
@timer_decorator(repeat=3)
def heavy_computation():
return sum(i**2 for i in range(10000))
类装饰器
除了函数装饰器,Python还支持类装饰器,通过实现__call__方法来实现:
class CountCalls:
def __init__(self, func):
self.func = func
self.call_count = 0
def __call__(self, *args, **kwargs):
self.call_count += 1
print(f"函数已被调用{self.call_count}次")
return self.func(*args, **kwargs)
@CountCalls
def process_data():
# 数据处理逻辑
pass
最佳实践
- 使用
functools.wraps保留原函数的元数据 - 保持装饰器的单一职责
- 考虑装饰器的执行顺序(从内到外)
装饰器是Python优雅设计哲学的完美体现,合理使用能让代码更加简洁、可维护。掌握这一特性,你将在Python开发中游刃有余。