Python函数加持:10个实用装饰器深入解析

图片[1]-Python函数加持:10个实用装饰器深入解析-山海云端论坛

小伙伴们!今天让我们一起深入探索一项让你的代码更加优雅、功能更强大的秘密武器——Python装饰器。装饰器就像是给你的函数穿上一层层华丽的功能外衣,让原本简单的函数瞬间变得高能且多功能。通过10个生动有趣的例子,我们将一窥装饰器的神奇魅力。

1、计时装饰器

首先,让我们介绍计时装饰器。这个装饰器的作用是测量函数执行的时间。在计算代码的性能或优化程序时,了解函数执行时间至关重要。下面是一个示例:

<code>import time def timer_decorator(func): def wrapper(*args, **kwargs): start_time = time.time() result = func(*args, **kwargs) end_time = time.time() print(f"函数 {func.__name__} 执行耗时: {end_time - start_time:.6f} 秒") return result return wrapper @timer_decorator def fibonacci(n): if n <= 0: return [] elif n == 1: return [0] elif n == 2: return [0, 1] else: fib_seq = [0, 1] for _ in range(2, n): fib_seq.append(fib_seq[-1] + fib_seq[-2]) return fib_seq # 使用装饰器测量fibonacci函数的执行时间 print(fibonacci(10))</code>

2、日志装饰器

接下来是日志装饰器,它可以自动记录函数调用情况,方便我们在调试和跟踪代码执行时使用。示例代码如下:

<code>import logging def log_decorator(func): def wrapper(*args, **kwargs): logging.info(f"调用函数 {func.__name__},参数: args={args}, kwargs={kwargs}") return func(*args, **kwargs) return wrapper logging.basicConfig(level=logging.INFO) @log_decorator def process_data(data): processed_data = data * 2 return processed_data # 使用装饰器记录process_data函数的调用情况 result = process_data(10) print(result)</code>

3、权限检查装饰器

权限检查装饰器用于验证用户是否有执行特定操作的权限。这在开发需要进行权限控制的应用程序时非常有用。示例代码如下:

<code>def permission_required(permission_level): def decorator(func): def wrapper(user): if user.permission >= permission_level: return func(user) else: raise PermissionError(f"用户权限不足,需要{permission_level}级以上才能执行此操作") return wrapper return decorator class User: def __init__(self, username, permission): self.username = username self.permission = permission @permission_required(3) def admin_only_operation(user): print(f"{user.username}正在执行管理员操作...") # 测试权限装饰器 user1 = User("Alice", 2) user2 = User("Bob", 3) admin_only_operation(user1) # 预期抛出PermissionError异常 admin_only_operation(user2) # 应该正常执行</code>

4、缓存装饰器

缓存装饰器可以提高函数计算结果的复用率,特别适用于那些计算结果不变的函数。示例代码如下:

<code>from functools import lru_cache @lru_cache(maxsize=100) def expensive_computation(arg): simulated_delay = arg * 0.1 # 模拟延迟时间 time.sleep(simulated_delay) return arg * arg # 使用缓存装饰器加速重复计算 print(expensive_computation(5)) # 第一次调用会计算并缓存结果 print(expensive_computation(5)) # 第二次调用直接返回缓存的结果</code>

5、事务处理装饰器

事务处理装饰器用于确保数据库操作的原子性,即要么所有操作都成功执行,要么都不执行。示例代码如下:

<code>class DatabaseWrapper: def __init__(self): self.transactions = [] def begin_transaction(self): self.transactions.append(True) def commit(self): self.transactions.pop() def rollback(self): if self.transactions: self.transactions.pop() def transactional(db): def decorator(func): def wrapper(*args, **kwargs): db.begin_transaction() try: result = func(db, *args, **kwargs) db.commit() return result except Exception as e: db.rollback() raise e from None return wrapper return decorator @transactional def update_user_profile(db, user_id, new_email): pass # 实际操作代码省略 # 使用事务装饰器保证数据操作的安全性 db = DatabaseWrapper() update_user_profile(db, 1, 'new@email.com')</code>

6、类型检查装饰器

类型检查装饰器用于确保函数传入参数的类型正确,可以帮助开发者在函数调用时捕获可能的参数类型错误。示例代码如下:

<code>def type_check_decorator(typespec): def decorator(func): def wrapper(*args, **kwargs): expected_args = typespec.get('args', []) expected_kwargs = typespec.get('kwargs', {}) for i, (arg, expected_type) in enumerate(zip(args, expected_args)): if not isinstance(arg, expected_type): raise TypeError(f"参数{i}的类型错误,期望{expected_type},但实际是{type(arg)}") for key, value in kwargs.items(): if key in expected_kwargs and not isinstance(value, expected_kwargs[key]): raise TypeError(f"关键字参数'{key}'的类型错误,期望{expected_kwargs[key]},但实际是{type(value)}") return func(*args, **kwargs) return wrapper return decorator @type_check_decorator({'args': [int, str], 'kwargs': {'age': int}}) def greet_user(name, age=None): print(f"Hello, {name}! You're {age} years old.") # 测试类型检查装饰器 greet_user("Alice", 25) # 正确类型,应正常执行 greet_user("Alice", "twenty-five") # 错误类型,应抛出TypeError异常</code>

7、性能优化装饰器

性能优化装饰器可以限制函数执行的频率,常用于节流操作,防止函数被频繁调用。示例代码如下:

<code>import time from threading import Lock class ThrottleDecorator: def __init__(self, interval_seconds): self.interval = interval_seconds self.last_called = 0 self.lock = Lock() def __call__(self, func): def wrapper(*args, **kwargs): with self.lock: now = time.time() if now - self.last_called > self.interval: self.last_called = now return func(*args, **kwargs) else: print(f"函数{func.__name__}在{self.interval}秒内被调用过于频繁,本次调用被忽略.") return wrapper @ThrottleDecorator(interval_seconds=3) def send_request(url): print(f"向{url}发送请求...") # 测试节流装饰器 for _ in range(10): send_request("http://example.com/api")</code>

8、重试机制装饰器

重试机制装饰器用于增加对可能会失败的操作的容错性,通过在函数执行失败时自动进行重试,提高函数的健壮性和可靠性。示例代码如下:

<code>from tenacity import retry, stop_after_attempt @retry(stop=stop_after_attempt(3)) def unreliable_function(): random_chance_of_failure = bool(random.getrandbits(1)) # 随机模拟成功或失败 if random_chance_of_failure: raise Exception("操作失败,稍后重试...") else: print("操作成功!") return True # 使用重试装饰器增加容错性 unreliable_function() # 将最多尝试3次直到成功</code>

9、调试信息装饰器

调试信息装饰器用于在函数执行前后打印调试信息,包括函数的参数和返回值,帮助开发者更好地理解函数的执行过程和结果。示例代码如下:

<code>def debug_decorator(func): def wrapper(*args, **kwargs): print(f"调用函数 {func.__name__} 开始,参数: args={args}, kwargs={kwargs}") result = func(*args, **kwargs) print(f"函数 {func.__name__} 结束,返回值: {result}") return result return wrapper @debug_decorator def calculate_average(numbers): return sum(numbers) / len(numbers) numbers_list = [1, 2, 3, 4, 5] average = calculate_average(numbers_list)</code>

10、性能分析装饰器

性能分析装饰器使用cProfile模块对函数的运行性能进行分析,可以帮助开发者找出函数中的性能瓶颈和优化空间。示例代码如下:

<code>import cProfile def profile_decorator(func): def wrapper(*args, **kwargs): profile = cProfile.Profile() profile.enable() result = func(*args, **kwargs) profile.disable() profile.print_stats(sort='cumulative') return result return wrapper @profile_decorator def complex_algorithm(arr): # 假设这是一个复杂的算法实现 pass # 实际算法代码省略 data = [...] # 输入数据 complex_algorithm(data)</code>

通过这些示例,我们展示了如何使用装饰器来增强函数的功能和性能,使得代码更加健壮、可靠、易于调试和优化。希望这些实用的装饰器能够帮助开发者提高编程效率和代码质量。

© 版权声明
THE END
喜欢就支持一下吧
点赞11 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容