一般實現python裝飾器都是采用方法的模式,看起來有點復雜,模式如下:
def send_msg_simple(url): def decorator(func): def wrapper(*args, **kw): func(*args, **kw) group_robot(url, "完畢:%s.%s" % (kw['db'], kw['table'])) return wrapper return decorator
但其實也可以采用類的方式,看起來邏輯更為清晰:
class DecoratorTest(object): #定義一個類 def __init__(self,func): self.__func = func def __call__(self): #定義call方法,當直接調用類的時候,運行這里。 print('pre msg') self.__func() print('post msg') @DecoratorTest def test(): print('主函數體') if __name__=='__main__': test()
下面是cookbook上的類裝飾器實現,略有不同
# 為了將裝飾器定義成一個類,你需要確保它實現了 __call__() 和 __get__() 方 法。 # 例如,下面的代碼定義了一個類,它在其他函數上放置一個簡單的記錄層: import types from functools import wraps class Profiled: def __init__(self, func): wraps(func)(self) self.ncalls = 0 def __call__(self, *args, **kwargs): self.ncalls += 1 return self.__wrapped__(*args, **kwargs) def __get__(self, instance, cls): if instance is None: return self else: return types.MethodType(self, instance) # 你可以將它當做一個普通的裝飾器來使用,在類里面或外面都可以: @Profiled def add(x, y): return x + y class Spam: @Profiled def bar(self, x): print(self, x)