Python でデコレータ関数を実装する

Document 对象参考手册Python3 実例

デコレータはPythonにおける強力なツールの一種で、元の関数コードを変更することなく、追加機能を追加することを可能にします。デコレータは本質的には関数であり、関数を引数として受け取り、新しい関数を返します。

実例

def my_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

@my_decorator
def say_hello():
    print("Hello!")

say_hello()

コード解析:

  1. my_decoratorはデコレータ関数であり、関数をfunc引数として受け取ります。
  2. wrapperは内部関数であり、呼び出しのfunc前と後にそれぞれ情報を出力します。
  3. my_decorator返すのはwrapper関数です。
  4. @my_decoratorはPythonのデコレータのシンタックスシュガーであり、以下と等価ですsay_hello = my_decorator(say_hello)。
  5. 私たちが呼び出すsay_hello()時、実際に呼び出されるのはwrapper関数であり、呼び出しのsay_hello前と後に情報を出力します。

出力結果:

Something is happening before the function is called.
Hello!
Something is happening after the function is called.

Document 对象参考手册Python3 実例

その他の拡張