面向切面编程在 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(
...
继续阅读
(31)