基于class的Python装饰器

Python 裝飾器通常用函數創建,請參閱另一篇相關文章(/python-aop-with-decorators),但這篇文章也展示了一個如何使用類別創建裝飾器的範例。

In [1]: def greet(name):
   ...:     print("Hi %s" % name)
   ...:

In [2]: greet("Andy")
Hi Andy

In [3]: class Polite(object):
   ...:     def __init__(self, func):
   ...:         self.func = func
   ...:     def __call__(self, *args, **kwargs):
   ...:         self.func(*args, **kwargs)
   ...:         print("Nice to meet you")
   ...:

In [4]: @Polite
   ...: def greet(name):
   ...:     print("Hi %s" % name)
   ...:

In [5]: greet("Andy")
Hi Andy
Nice to meet you

python aspect oriented programming