标签:wrapper result 扩展 for margin app 运行 out running
python装饰器就是对已有函数的功能扩展.
ef Before(request,kargs):
print ‘before‘
def After(request,kargs):
print ‘after‘
def Filter(before_func,after_func):
def outer(main_func):
def wrapper(request,kargs):
before_result = before_func(request,kargs)
if(before_result != None):
return before_result;
main_result = main_func(request,kargs)
if(main_result != None):
return main_result;
after_result = after_func(request,kargs)
if(after_result != None):
return after_result;
return wrapper
return outer
@Filter(Before, After)
def Index(request,kargs):
print ‘index‘
Index()
1.@Filter(Before, After) 这个首先执行Filter(Before, After)函数,然后返回一个装饰器outer
2.这样@Filter(Before, After)就等于@Outer
3.@outer把下面被装饰的Index()函数名作为参数运行outer(Index)
4.得到的返回值wrapper复制给Index()
5.开始执行最下面的Index()语句,由于Index被复制成为了wrapper,所以等于运行了wrapper,于是切入装饰器内部,开始执行wrapper函数.
标签:wrapper result 扩展 for margin app 运行 out running
原文地址:http://www.cnblogs.com/jack410/p/6483724.html