python面试
题目描述
# 有一个函数bar(),偶尔会抛出超时异常(TimeoutError) # 请完成retry,使bar()在遇到这种异常时可以重试指定的次数 (1p) def retry(exception: Exception, max_retries: int): pass class TimeoutError(Exception): pass @retry(TimeoutError, 10) def bar(*args, **kwargs): import random if random.random() < 0.5: raise TimeoutError("bar failed")
解答1
# 典型的装饰器,但是这个是带参数的装饰器 from functools import wraps def retry(exception: Exception, max_retires: int): def func_wrapper(func): @wraps(func) def wrapper(*args, **kwargs): for _ in range(max_retires): try: return func(*args, **kwargs) except exception: print(f"_ is {_+1}尝试") return None return wrapper return func_wrapper
解答2
class Retry: def __init__(self, exception: Exception, max_retires: int) -> None: self.exception = exception self.max_retires = max_retires def __call__(self, func): @wraps(func) def wrapper(*args, **kwargs): for _ in range(self.max_retires): try: return func(*args, **kwargs) except self.exception: print(f"第{_+1}次尝试") return None return wrapper