Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
学ぶ Pythonでパラメータ付きデコレータを使用する | Pythonデコレータの習得
Pythonにおける関数型プログラミングの概念

bookPythonでパラメータ付きデコレータを使用する

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

パラメータ付きデコレータは、Pythonにおける高度な機能であり、デコレータに追加の引数を渡すことで柔軟性を高めることができます。以下は、この概念を説明する実用的な例です。

基本的なデコレータ構造

まず、基本的なデコレータ構造から始めます。

123456789101112
def simple_decorator(func): def wrapper(): print("Something is happening before the function is called.") func() print("Something is happening after the function is called.") return wrapper @simple_decorator def say_hello(): print("Hello!") say_hello()
copy

この例では、simple_decoratorsay_hello 関数の動作を変更する通常のデコレータです。

パラメータ付きデコレータ

次に、パラメータを受け取るデコレータを作成します。

12345678910111213
def decorator_with_args(arg1, arg2): def decorator(func): def wrapper(*args, **kwargs): print(f"Decorator args: {arg1}, {arg2}") return func(*args, **kwargs) return wrapper return decorator @decorator_with_args("hello", 42) def print_numbers(a, b): print(a + b) print_numbers(10, 5)
copy

この例では、decorator_with_args はパラメータ (arg1, arg2) を受け取るデコレータファクトリであり、実際のデコレータ (decorator) を返します。wrapper 関数は、デコレートされた関数(print_numbers)の動作を変更する役割を持ちます。

解説

  • decorator_with_args は引数 ("hello", 42) で呼び出されます;
  • これにより decorator 関数が返されます;
  • decorator は関数 print_numbers を受け取り、wrapper 関数を返します;
  • wrapperdecorator_with_args の引数と print_numbers の引数の両方にアクセスできます。

この構造により、デコレータにカスタム引数を渡して動作を変更できるため、柔軟性と再利用性が向上します。

すべて明確でしたか?

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

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

セクション 5.  4

AIに質問する

expand

AIに質問する

ChatGPT

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

セクション 5.  4
some-alt