一般实现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()
来源:https://www.cnblogs.com/wangbin2188/p/12098380.html