Created
October 22, 2014 03:00
-
-
Save smison/a5bf5bc10d7bcc8b58e3 to your computer and use it in GitHub Desktop.
[python] @: デコレータ
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
- [python] @: デコレータ | |
- Python - デコレータ http://www17.atpages.jp/~lambda7/py/decorator.html | |
- Pythonのデコレータを理解するための12Step http://qiita.com/_rdtr/items/d3bc1a8d4b7eb375c368 | |
デコレータとは「関数を引数に取り, 引き換えに新たな関数を返すcallable(*)」。 | |
より分かりやすく言えば「@wrapperで指定したwrapper(func)な関数で、直下の関数に機能追加できる」機能。 | |
もとの関数funcの引数は「*args, **kwargs」で利用可。 | |
=================================================== | |
import time | |
def instrument(func): | |
def wrapper(*args, **kwargs): # 補: こいつは周辺(def instrument内)の変数の値を記憶していて、closureとよばれる関数 | |
import time # 関数の再利用を考慮して再import | |
start = time.time() | |
result = func(*args, **kwargs) | |
end = time.time() | |
print(func.__name__, ":", end - start) | |
return result | |
return wrapper | |
@instrument | |
def foo(): | |
time.sleep(1) | |
foo() | |
=================================================== | |
#=> ('foo', ':', 1.0012121200561523) | |
fooに時間計算機能と表示機能が追加された | |
(*)callableとは引数を取って結果を返す, 呼び出し可能なオブジェクトの総称を指します. | |
functionはもちろんclassやmethod, generatorなどもcallableです. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment