Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
学ぶ デコレータの連結と積み重ね | Pythonイテレーターとデコレーターの習得
Pythonにおける関数型プログラミングの概念

bookデコレータの連結と積み重ね

メニューを表示するにはスワイプしてください

Pythonでデコレーターを使用する際、1つの関数に複数のデコレーターを適用する必要がある場合があります。これはデコレーターの積み重ね(スタッキング)またはチェイニングと呼ばれます。デコレーターを積み重ねる方法は、関数定義の直前に複数のデコレーター行を連続して記述することです。デコレーターの積み重ね順序は重要であり、関数がどのようにラップされ、各デコレーターがどのように相互作用するかに影響します。関数に最も近いデコレーターが最初に適用され、その後、各デコレーターが前のデコレーターの結果をラップします。つまり、スタックの一番上のデコレーターが最も外側のラッパーとなり、関数に最も近いものが最も内側になります。

以下の例では、2つのデコレーター decorator_onedecorator_two を定義し、greet という関数の上に積み重ねています。積み重ねる順序によって、デコレーターがどのように適用されるかが決まります。

123456789101112131415161718192021222324252627
# Prints messages before and after the function call def decorator_one(func): def wrapper(*args, **kwargs): print("Decorator One: Before") result = func(*args, **kwargs) print("Decorator One: After") return result return wrapper # Also prints messages before and after the function call def decorator_two(func): def wrapper(*args, **kwargs): print("Decorator Two: Before") result = func(*args, **kwargs) print("Decorator Two: After") return result return wrapper # Stacking decorators # decorator_two is applied first (innermost), # then decorator_one wraps the result (outermost) @decorator_one @decorator_two def greet(name): print(f"Hello, {name}!") greet("Alice")
copy
Note
注意

decorator_two が最初に greet に適用され、その後に decorator_one がその結果をラップします。つまり、関数に最も近いデコレータが最も内側となり、最上部のデコレータが最も外側となります。スタックする順序は重要であり、デコレートされた関数の動作に影響します。

question mark

Python で積み重ねられたデコレータはどの順序で適用されますか?

すべての正しい答えを選択

すべて明確でしたか?

どのように改善できますか?

フィードバックありがとうございます!

セクション 4.  5

AIに質問する

expand

AIに質問する

ChatGPT

何でも質問するか、提案された質問の1つを試してチャットを始めてください

セクション 4.  5
some-alt