『エキスパートPythonプログラミング改訂2版』を読みながら、デコレータをクラスとして実装するサンプルプログラムを書いてみる。
■プログラム名 kakko_deco.py
class KakkoDecorator:
def __init__(self, function):
self.function = function
def __call__(self, *args, **kwargs):
# 関数呼び出し前の処理
result = self.function(*args, **kwargs)
# 呼出し後の処理
result = '[' + result + ']'
return result
# デコレートされる関数
@KakkoDecorator
def get_message():
return 'Hello, Decorator.'
if __name__ == '__main__':
msg = get_message()
print(msg)
■実行結果
$ python kakko_deco.py [Hello, Decorator.]