Day 153再試行付きの処理をデコレータで作る

2026-07-27 JST ・ 難易度: 実用 ・ カテゴリ: 実用パターン

Pythonコード

1def retry(max_attempts=3):2    def decorator(func):3        def wrapper(*args, **kwargs):4            attempts = 05            while attempts < max_attempts:6                try:7                    return func(*args, **kwargs)8                except Exception as e:9                    attempts += 110                    print(f'再試行{attempts}回目: {e}')11            print('最大再試行回数に達しました')12        return wrapper13    return decorator14 15@retry(max_attempts=5)16def divide(a, b):17    return a / b18 19try:20    num1 = float(input('数字を入力してください: '))21    num2 = float(input('もう一つ数字を入力してください: '))22    result = divide(num1, num2)23    print(f'{num1} / {num2} = {result}')24except ValueError:25    print('数値以外の入力です')26except ZeroDivisionError:27    print('0で割ることはできません')

解説

次に試してみよう