1、日志记录:
-
记录函数的调用信息、参数和返回值。
def log_decorator(func):def wrapper(*args, **kwargs):print(f"Calling {func.__name__} with args: {args}, kwargs: {kwargs}")result = func(*args, **kwargs)print(f"{func.__name__} returned: {result}")return resultreturn wrapper@log_decorator
def add(a, b):return a + badd(2, 3)
2、性能计时:
-
计算函数的执行时间。
import timedef timer_decorator(func):def wrapper(*args, **kwargs):start_time = time.time()result = func(*args, **kwargs)end_time = time.time()print(f"{func.__name__} took {end_time - start_time:.4f} seconds")return resultreturn wrapper@timer_decorator
def slow_function():time.sleep(2)slow_function()
3、权限验证:
-
在函数执行前检查用户权限。
def check_permission(func):def wrapper(user, *args, **kwargs):if user == "admin":return func(*args, **kwargs)else:raise PermissionError("Permission denied")return wrapper@check_permission
def delete_file(user, filename):print(f"Deleting {filename}")delete_file("admin", "test.txt")
4、缓存:
-
缓存函数的返回值,避免重复计算。
def cache_decorator(func):cache = {}def wrapper(*args):if args in cache:return cache[args]result = func(*args)cache[args] = resultreturn resultreturn wrapper@cache_decorator
def fibonacci(n):if n <= 1:return nreturn fibonacci(n-1) + fibonacci(n-2)print(fibonacci(10))
5、重试机制:
-
在函数失败时自动重试。
import randomdef retry_decorator(max_retries=3):def decorator(func):def wrapper(*args, **kwargs):retries = 0while retries < max_retries:try:return func(*args, **kwargs)except Exception as e:retries += 1print(f"Retry {retries}/{max_retries} for {func.__name__}")raise Exception("Max retries exceeded")return wrapperreturn decorator@retry_decorator(max_retries=5)
def unreliable_function():if random.random() < 0.5:raise ValueError("Something went wrong")return "Success"unreliable_function()
6、类装饰器
装饰器不仅可以用于函数,还可以用于类。类装饰器接受一个类作为参数,并返回修改后的类。
def add_method(cls):def new_method(self):return "This is a new method"cls.new_method = new_methodreturn cls@add_method
class MyClass:passobj = MyClass()
print(obj.new_method()) # 输出: This is a new method