パラメータ化デコレータの作成
メニューを表示するにはスワイプしてください
デコレーターの動作を入力に応じて変えたい場合、パラメータ付きデコレーターを作成する必要があります。通常のデコレーターは関数のみを引数として受け取りますが、パラメータ付きデコレーターは独自の引数を受け取り、その動作を動的に制御できます。これは、異なる設定でデコレーターを複数の状況で再利用したい場合に特に便利です。
パラメータ付きデコレーターの構造:
- 外側の関数がデコレーターの引数を受け取る;
- 中間の関数が実際にデコレーションされる関数を受け取るデコレーター;
- 内側の関数が元の関数の実行をラップして制御する。
この階層構造により、デコレーターに引数を渡すことができ、デコレーションされた関数が呼び出されたときにその引数が利用可能になります。
12345678910111213141516171819202122# Outer function: accepts the decorator argument 'times' def repeat(times): # The actual decorator that takes the function to be decorated def decorator(func): # Inner function: wraps and controls the execution of 'func' def wrapper(*args, **kwargs): result = None # Call the original function 'times' times for _ in range(times): result = func(*args, **kwargs) return result # Return the wrapper to replace the original function return wrapper # Return the decorator function return decorator # Apply the repeat decorator @repeat(3) def say_hello(): print("Hello!") say_hello()
1. パラメータ付きデコレーターは通常のデコレーターとどのように異なりますか?
2. なぜデコレータに引数を渡す必要があるのか?
すべて明確でしたか?
フィードバックありがとうございます!
セクション 4. 章 3
AIに質問する
AIに質問する
何でも質問するか、提案された質問の1つを試してチャットを始めてください
セクション 4. 章 3