Python 装饰器高级应用指南
1. 装饰器基础
装饰器是 Python 中一种强大的语法特性,它允许我们在不修改原函数代码的情况下,增强函数的功能。
def simple_decorator(func):
def wrapper(*args, **kwargs):
print("Before function execution")
result = func(*args, **kwargs)
print("After function execution")
return result
return wrapper
@simple_decorator
def hello():
print("Hello, World!")
hello()
2. 带参数的装饰器
2.1 装饰器工厂
def repeat(n):
def decorator(func):
def wrapper(*args, **kwargs):
for _ in range(n):
result = func(*args, **kwargs)
return result
return wrapper
return decorator
@repeat(3)
def hello():
print("Hello, World!")
hello()
2.2 带多个参数的装饰器
def log(level, message):
def decorator(func):
def wrapper(*args, **kwargs):
print(f"[{level}]: {message}")
result = func(*args, **kwargs)
return result
return wrapper
return decorator
@log("INFO", "Function is called")
def add(a, b):
return a + b
print(add(1, 2))
3. 类装饰器
3.1 基本类装饰器
class Timer:
def __init__(self, func):
self.func = func
def __call__(self, *args, **kwargs):
import time
start = time.time()
result = self.func(*args, **kwargs)
end = time.time()
print(f"Function {self.func.__name__} took {end - start:.4f} seconds")
return result
@Timer
def slow_function():
import time
time.sleep(1)
print("Function executed")
slow_function()
3.2 带参数的类装饰器
class Logger:
def __init__(self, log_file):
self.log_file = log_file
def __call__(self, func):
def wrapper(*args, **kwargs):
result = func(*args, **kwargs)
with open(self.log_file, "a") as f:
f.write(f"Function {func.__name__} called with args {args}, kwargs {kwargs}\n")
return result
return wrapper
@Logger("app.log")
def add(a, b):
return a + b
print(add(1, 2))
4. 装饰器的高级应用
4.1 装饰器链
def decorator1(func):
def wrapper(*args, **kwargs):
print("Decorator 1")
result = func(*args, **kwargs)
return result
return wrapper
def decorator2(func):
def wrapper(*args, **kwargs):
print("Decorator 2")
result = func(*args, **kwargs)
return result
return wrapper
@decorator1
@decorator2
def hello():
print("Hello, World!")
hello()
4.2 保留函数元数据
import functools
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
print("Before function execution")
result = func(*args, **kwargs)
print("After function execution")
return result
return wrapper
@decorator
def hello():
"""Hello function"""
print("Hello, World!")
print(hello.__name__)
print(hello.__doc__)
4.3 装饰器用于缓存
import functools
def cache(func):
cache_data = {}
@functools.wraps(func)
def wrapper(*args, **kwargs):
key = str(args) + str(kwargs)
if key not in cache_data:
cache_data[key] = func(*args, **kwargs)
return cache_data[key]
return wrapper
@cache
def fibonacci(n):
if n <= 1:
return n
return fibonacci(n-1) + fibonacci(n-2)
print(fibonacci(30))
5. 实际应用场景
5.1 权限验证
def requires_permission(permission):
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
# 假设 current_user 是当前登录用户
current_user = {"permissions": ["read", "write"]}
if permission not in current_user["permissions"]:
raise PermissionError(f"User does not have {permission} permission")
return func(*args, **kwargs)
return wrapper
return decorator
@requires_permission("write")
def create_post(title, content):
print(f"Creating post: {title}")
return {"title": title, "content": content}
create_post("Hello", "World")
5.2 日志记录
def log_function(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
import logging
logging.basicConfig(level=logging.INFO)
logging.info(f"Calling {func.__name__} with args: {args}, kwargs: {kwargs}")
result = func(*args, **kwargs)
logging.info(f"{func.__name__} returned: {result}")
return result
return wrapper
@log_function
def add(a, b):
return a + b
print(add(1, 2))
5.3 性能监控
def monitor_performance(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
import time
start_time = time.time()
result = func(*args, **kwargs)
end_time = time.time()
print(f"{func.__name__} took {end_time - start_time:.4f} seconds")
return result
return wrapper
@monitor_performance
def slow_function():
import time
time.sleep(1)
return "Done"
print(slow_function())
6. 最佳实践
- 使用
functools.wraps:保留原函数的元数据,如函数名、文档字符串等。 - 保持装饰器简洁:装饰器应该专注于单一功能,避免过于复杂。
- 使用装饰器工厂:当装饰器需要参数时,使用装饰器工厂模式。
- 文档化装饰器:为装饰器添加清晰的文档,说明其功能和用法。
- 测试装饰器:确保装饰器在各种场景下都能正常工作。
- 避免过度使用:装饰器虽然强大,但过度使用会使代码难以理解。
- 考虑性能影响:某些装饰器(如缓存)可能会影响性能,需要权衡使用。
7. 总结
装饰器是 Python 中一种强大的特性,它允许我们以一种简洁、优雅的方式增强函数的功能。通过掌握装饰器的高级应用,我们可以编写更加模块化、可维护的代码。
在实际应用中,装饰器可以用于权限验证、日志记录、性能监控、缓存等多种场景,大大提高代码的复用性和可维护性。
希望本文对你理解和应用 Python 装饰器有所帮助!
1680



被折叠的 条评论
为什么被折叠?



