次に例を示します。
class ContextDecorator(object):
def __init__(self, foo, bar):
self.foo = foo
self.bar = bar
print("init", foo, bar)
def __call__(self, f):
print("call")
def wrapped_f():
print("about to call")
f()
print("done calling")
return wrapped_f
def __enter__(self):
print("enter")
def __exit__(self, exc_type, exc_val, exc_tb):
print("exit")
with ContextDecorator(1, 2):
print("with")
@ContextDecorator(3, 4)
def sample():
print("sample")
sample()
これは以下を出力します:
init 1 2
enter
with
exit
init 3 4
call
about to call
sample
done calling