Pythonデコレーターの構文:デコレーターの記述と適用
メニューを表示するにはスワイプしてください
デコレーターは、関数を引数として受け取り、その関数をラッパー関数内で実行する仕組み。
デコレーターを適用するには、**@**記号の後にデコレーター関数名を記述し、修飾したい関数の直前に配置する。以下はその例:
def decorator(func):
...
# First method
@decorator
add(a,b):
print(f"Function add: {a} + {b}")
add(2, 3)
# Second method
add(a,b):
print(f"Function add: {a} + {b}")
inner = decorator(add)
inner(2, 3)
この例では、どちらの方法も同じ結果となる。@記号を使う第一の方法は、decoratorsを適用するより読みやすく簡潔な方法であり、「シンタックスシュガー」と呼ばれることが多い。
デコレーター内でwrapperという名前のネストされた関数を使用するのが一般的。
柔軟なデコレータ:多様な関数引数への対応
関数はしばしば異なる数の引数を必要とします。
異なる引数の数を持つ関数に適用できるデコレータを作成するには、*args 関数内で **kwargs および wrapper() を利用するのが効果的です。
1234567891011121314151617181920212223242526272829303132333435def indicate(func): def wrapper(*args, **kwargs): print("=" * 15) print("Taken arguments:", *args, kwargs) result = func(*args, **kwargs) print("=" * 15) return result return wrapper @indicate def avg_two(a, b): """Calculate the average of two numbers""" return round((a + b) / 2, 1) @indicate def avg_three(a, b, c): """Calculate the average of three numbers""" return round((a + b + c) / 3, 1) @indicate def avg_many_kwargs(**kwargs): """Calculate the average of multiple numbers in a dictionary""" keys = 0 total = 0 for value in kwargs.values(): keys += 1 total += value return round(total / keys, 1) print("Returned:", avg_two(14, 21), "\n") print("Returned:", avg_three(225, 12, 11), "\n") print("Returned:", avg_many_kwargs(first=51, second=11, third=47, fourth=93))
すべて明確でしたか?
フィードバックありがとうございます!
セクション 5. 章 2
AIに質問する
AIに質問する
何でも質問するか、提案された質問の1つを試してチャットを始めてください
セクション 5. 章 2