这期内容当中小编将会给大家带来有关如何使用Python装饰器,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。
示例一:
def outer(fun):
print fun
def wrapper(arg):
result=fun(arg)
print 'over!'
return result
return wrapper
@outer
def func1(arg):
print 'func1',arg
return 'very good!'
response=func1('python')
print response
print func1
运行结果:
<function func1 at 0x02A67D70>
func1 python
over!
very good!
<function wrapper at 0x02A67CF0>
示例二:
#!/usr/bin/env python
#coding:utf-8
def Filter(before_func,after_func):
print before_func
print after_func
def outer(main_func):
print 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
def before(request,kargs):
print request,kargs,'之前!'
def after(request,kargs):
print request,kargs,'之后!'
@Filter(before,after)
def main(request,kargs):
print request,kargs
main('hello','python')
print main
运行结果:
<function before at 0x02AC7BF0>
<function after at 0x02AC7C30>
<function main at 0x02AC7CF0>
hello python 之前!
hello python
hello python 之后!
<function wrapper at 0x02AC7D30>
上述就是小编为大家分享的如何使用Python装饰器了,如果刚好有类似的疑惑,不妨参照上述分析进行理解。如果想知道更多相关知识,欢迎关注天达云行业资讯频道。