装饰器(Decorator)是一种用于修改或增强函数行为的技术。在Python中,装饰器是函数或类,它可以接受一个函数作为输入,并返回一个新的函数,通常在新函数中对原函数进行一些额外的操作。以下是一些常见的装饰器应用场景:
日志记录:
def log_decorator(func):
def wrapper(*args, **kwargs):
print(f"Calling function {func.__name__} with arguments {args}, {kwargs}")
result = func(*args, **kwargs)
print(f"Function {func.__name__} returned {result}")
return result
return wrapper
@log_decorator
def add(a, b):
return a + b
add(2, 3)
性能分析:
import time
def timing_decorator(func):
def wrapper(*args, **kwargs):
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
@timing_decorator
def slow_function():
time.sleep(2)
print("Function executed")
slow_function()
缓存结果:
def cache_decorator(func):
cache = {}
def wrapper(*args):
if args in cache:
print(f"Using cached result for {func.__name__}{args}")
return cache[args]
else:
result = func(*args)
cache[args] = result
print(f"Caching result for {func.__name__}{args}")
return result
return wrapper
@cache_decorator
def expensive_calculation(x, y):
time.sleep(2)
return x + y
print(expensive_calculation(2, 3))
print(expensive_calculation(2, 3)) # 使用缓存的结果
身份验证:
def authenticate_decorator(func):
def wrapper(*args, **kwargs):
# 检查身份验证逻辑
if is_authenticated():
return func(*args, **kwargs)
else:
raise PermissionError("Authentication failed")
return wrapper
@authenticate_decorator
def secure_function():
print("This function requires authentication")
secure_function()
请求处理:
from flask import Flask
app = Flask(__name__)
def route_decorator(func):
def wrapper():
# 处理请求逻辑
result = func()
return f"Result: {result}"
return wrapper
@app.route('/')
@route_decorator
def home():
return "Hello, World!"
if __name__ == '__main__':
app.run()
这些是一些装饰器在Python中的常见应用场景。装饰器提供了一种灵活的方式来修改或增强函数的行为,使得代码更加模块化和可维护。在实际开发中,你还可以组合多个装饰器,以便在同一个函数上应用多个功能。