Python でデコレータ関数を実装する
デコレータは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()
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()
コード解析:
my_decoratorはデコレータ関数であり、関数をfunc引数として受け取ります。wrapperは内部関数であり、呼び出しのfunc前と後にそれぞれ情報を出力します。my_decorator返すのはwrapper関数です。@my_decoratorはPythonのデコレータのシンタックスシュガーであり、以下と等価ですsay_hello = my_decorator(say_hello)。- 私たちが呼び出す
say_hello()時、実際に呼び出されるのはwrapper関数であり、呼び出しのsay_hello前と後に情報を出力します。
出力結果:
Something is happening before the function is called. Hello! Something is happening after the function is called.その他の拡張
Python3 実例