标签:
装饰器是函数,只不过该函数可以具有特殊的含义,装饰器用来装饰函数或类,使用装饰器可以在函数执行前和执行后添加相应操作。
1 def wrapper(func): 2 def result(): 3 print ‘before‘ 4 func() 5 print ‘after‘ 6 return result 7 8 @wrapper 9 def foo(): 10 print ‘foo‘
1 import functools 2 3 4 def wrapper(func): 5 @functools.wraps(func) 6 def wrapper(): 7 print ‘before‘ 8 func() 9 print ‘after‘ 10 return wrapper 11 12 @wrapper 13 def foo(): 14 print ‘foo‘
1 #!/usr/bin/env python 2 #coding:utf-8 3 4 def Before(request,kargs): 5 print ‘before‘ 6 7 def After(request,kargs): 8 print ‘after‘ 9 10 11 def Filter(before_func,after_func): 12 def outer(main_func): 13 def wrapper(request,kargs): 14 15 before_result = before_func(request,kargs) 16 if(before_result != None): 17 return before_result; 18 19 main_result = main_func(request,kargs) 20 if(main_result != None): 21 return main_result; 22 23 after_result = after_func(request,kargs) 24 if(after_result != None): 25 return after_result; 26 27 return wrapper 28 return outer 29 30 @Filter(Before, After) 31 def Index(request,kargs): 32 print ‘index‘ 33 34 35 if __name__ == ‘__main__‘: 36 Index(1,2)
标签:
原文地址:http://www.cnblogs.com/sundi/p/5236759.html