LoginSignup
4
2

More than 5 years have passed since last update.

Pythonのデコレータについての適当な説明

Last updated at Posted at 2017-05-17

デコレータとはデコレータ用の関数である関数を装飾し,装飾された関数にすり替えてくれる機能です.

例えば以下のようなデコレータ用の関数を用意します.

def my_decorator(func):
    def decorated_my_func(*args, **kwargs):
        print("デコレートしました")
        func(*args, **kwargs)
    return decorated_my_func

そして普通の関数を上の関数でデコレートして宣言します.

@my_decorator
def my_func(str):
    print(str)

そして実行すると

>>> my_func("ああああああ")
デコレートしました
ああああああ

となります.つまりmy_func()宣言時に@my_decoratorをつけることによって

>>> my_func = my_decorator(my_func)
... my_func("ああああああ")
デコレートしました
ああああああ

と同じことをしてくれるのがデコレータです.

4
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
2