#装饰函数和方法
def foo():
print 'foo' def foo(): print 'before do something' print 'foo' print 'after' def foo(): print 'foo' def wrapper(func): print 'before' func() print 'after' wrapper(foo) def foo(): print 'foo' def wrapper(func): def result(): print 'before' func() print 'after' return result Do = wrapper(foo) Do() def wrapper(func): def result(): print 'before' func() print 'after' return result @wrapper def foo(): print 'foo' foo() |
#带参数的装饰器
#在函数执行前后,执行任意函数
#!/usr/bin/env python #coding:utf-8 def 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' if __name__ = = '__main__' : Index( 1 , 2 ) |
def outer(fun):
def wrapper(arg):
print '验证'
result = fun(arg)
print 'ok'
return result
return wrapper
@outer
def Func1(arg):
print 'func1',arg
return 'return'
#@outer = outer(Func1)
response = Func1('li')
print response
#装饰类