基於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