装饰器(Decorator)是 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.
- 带参数的装饰器
def log_execution_time(func):
def wrapper(*args, **kwargs):
import time
start_time = time.time()
result = func(*args, **kwargs)
end_time = time.time()
print(f"Function {func.__name__} took {end_time - start_time} seconds")
return result
return wrapper
@log_execution_time
def calculate_sum(n):
return sum(range(n))
# 使用
result = calculate_sum(1000000)
- 实际应用示例
a、计时装饰器:
def timer(func):
def wrapper(*args, **kwargs):
import time
start = time.time()
result = func(*args, **kwargs)
print(f"Function {func.__name__} took {time.time() - start:.2f} seconds")
return result
return wrapper
@timer
def slow_function():
import time
time.sleep(1)
2、缓存装饰器:
2. **缓存装饰器**:
```python
def cache(func):
_cache = {}
def wrapper(*args):
if args not in _cache:
_cache[args] = func(*args)
return _cache[args]
return wrapper
@cache
def fibonacci(n):
if n < 2:
return n
return fibonacci(n-1) + fibonacci(n-2)
c、权限检查装饰器:
def require_auth(func):
def wrapper(*args, **kwargs):
if not is_authenticated(): # 假设有这个函数
raise Exception("Authentication required")
return func(*args, **kwargs)
return wrapper
@require_auth
def sensitive_operation():
print("Performing sensitive operation")
- 类装饰器
class CountCalls:
def __init__(self, func):
self.func = func
self.count = 0
def __call__(self, *args, **kwargs):
self.count += 1
print(f"Call {self.count} of {self.func.__name__}")
return self.func(*args, **kwargs)
@CountCalls
def say_hello():
print("Hello!")
- 多个装饰器
def bold(func):
def wrapper():
return "<b>" + func() + "</b>"
return wrapper
def italic(func):
def wrapper():
return "<i>" + func() + "</i>"
return wrapper
@bold
@italic
def greet():
return "Hello!"
# 输出:<b><i>Hello!</i></b>
装饰器是 Python 中非常强大的特性,可以用来:
- 添加日志
- 性能测量
- 访问控制
- 缓存
- 参数验证
等多种用途。