デコレータは通常、ラッパー関数を返します。ラップされた関数を呼び出した後、ロジックをラッパー関数に入れるだけです。
def audit_action(action):
def decorator_func(func):
def wrapper_func(*args, **kwargs):
# Invoke the wrapped function first
retval = func(*args, **kwargs)
# Now do something here with retval and/or action
print('In wrapper_func, handling action {!r} after wrapped function returned {!r}'.format(action, retval))
return retval
return wrapper_func
return decorator_func
( )を装飾するために使用されるaudit_action(action='did something')
スコープ付きのを返すデコレータファクトリもそうです。decorator_func
do_something
do_something = decorator_func(do_something)
装飾後、do_something
参照はに置き換えられましたwrapper_func
。呼び出すwrapper_func()
と元のコードdo_something()
が呼び出され、ラッパーfuncのコードで処理を実行できます。
上記のコードをサンプル関数と組み合わせると、次の出力が得られます。
>>> do_something('foo')
In wrapper_func, handling action 'did something' after wrapped function returned 'bar'
'bar'