本文共 4454 字,大约阅读时间需要 14 分钟。
Python装饰器是一种强大的功能扩展工具,能够在不修改源代码的情况下为函数增添功能。它们通常用于日志记录、性能测试、权限控制、缓存管理等场景。
import time@timerdef example_function(): time.sleep(1)example_function()
输出示例:
example_function executed in 1.0021049690246582 seconds import logginglogging.basicConfig(level=logging.INFO)@log_executiondef add(a, b): return a + badd(3, 5)
输出示例:
INFO:root:Calling add with args: (3, 5), kwargs: {}INFO:root:add returned: 8 functools.lru_cache 实现结果缓存,避免重复计算,提升性能。from functools import lru_cache@lru_cache(maxsize=None)def fibonacci(n): if n < 2: return n return fibonacci(n-1) + fibonacci(n-2)print(fibonacci(10))
输出示例:
fibonacci(10) returned 55 def type_check(*arg_types): def decorator(func): def wrapper(*args, **kwargs): for arg, expected_type in zip(args, arg_types): if not isinstance(arg, expected_type): raise TypeError(f"Argument {arg} is not of type {expected_type}") return func(*args, **kwargs) return wrapper return decorator@type_check(int, int)def multiply(x, y): return x * yprint(multiply(2, 3)) 输出示例:
6 class SingletonMeta(type): _instances = {} def __call__(cls, *args, **kwargs): if cls not in cls._instances: cls._instances[cls] = super().__call__(*args, **kwargs) return cls._instances[cls]class Singleton(metaclass=SingletonMeta): passs1 = Singleton()s2 = Singleton()print(s1 is s2) 输出示例:
True import randomdef retry_on_exception(max_retries=3, exceptions=(Exception,), delay=1): def decorator(func): def wrapper(*args, **kwargs): retries = 0 while retries < max_retries: try: return func(*args, **kwargs) except exceptions as e: print(f"Caught {e}. Retrying...") retries += 1 time.sleep(delay) raise Exception("Max retries exceeded.") return wrapper return decorator@retry_on_exception(max_retries=3)def might_fail(): if random.randint(0, 2) == 0: raise ValueError("Failed.") print("Success!")might_fail() 输出示例:
Caught ValueError('Failed.'). Retrying...Caught ValueError('Failed.'). Retrying...Caught ValueError('Failed.'). Retrying...Max retries exceeded.或Success! cProfile 工具分析函数执行性能。import cProfiledef profile(func): def wrapper(*args, **kwargs): profiler = cProfile.Profile() profiler.enable() result = func(*args, **kwargs) profiler.disable() profiler.print_stats() return result return wrapper@profiledef dummy_function(n): return sum([i**2 for i in range(n)])dummy_function(100000)
输出示例:
函数执行性能统计信息。def authenticate(user_required=True): def decorator(func): def wrapper(*args, **kwargs): if not user_required or user_is_logged_in(): return func(*args, **kwargs) else: raise PermissionError("User not authenticated.") return wrapper return decorator@authenticatedef sensitive_operation(): print("Sensitive operation performed.")# 假设已经登录sensitive_operation() 输出示例:
Sensitive operation performed. import asyncioasync def async_decorator(func): async def wrapper(*args, **kwargs): print("Starting async task...") result = await func(*args, **kwargs) print("Async task finished.") return result return wrapper@async_decoratorasync def long_running_task(): await asyncio.sleep(2) return "Task done."asyncio.run(long_running_task()) 输出示例:
Starting async task...Async task finished. def validate_input(minimum=0, maximum=100): def decorator(func): def wrapper(value): if not (minimum <= value <= maximum): raise ValueError(f"Value must be between {minimum} and {maximum}") return func(value) return wrapper return decorator@validate_input(1, 10)def process_value(value): print(f"Processing value: {value}")process_value(5) 输出示例:
Processing value: 5 转载地址:http://rsafk.baihongyu.com/