面向切面编程在 Python 中一部分体现为装饰器。
由于 Python 中一切皆对象,装饰器的使用方法也因此多种多样,下文介绍装饰器的四种写法。
用函数装饰函数 def retry(func: Optional[Callable] = None, duration: timedelta = timedelta(seconds=2), limit: int = 10) -> Callable: if not func: return functools.partial(retry, duration=duration, limit=limit) @functools.wraps(func) def _func(*args, **kwargs): duration_seconds = duration.total_seconds() count = 1 while count <= limit: try: result = func(*args, **kwargs) return result except: count += 1 time.sleep(duration_seconds) continue return _func class TestRetry(unittest.TestCase): @staticmethod def generate_test_function(limit, retry_decorator): retry_count = [0] @retry_decorator(limit=5, duration=timedelta(seconds=0)) def my_test(): retry_count[0] += 1 if retry_count[0] < limit: raise Exception("Test failed") else: return retry_count return my_test def test_function_decoration(self): for i in range(100): exception_count = random.