python装饰器

Posted 你居然是华神

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python装饰器相关的知识,希望对你有一定的参考价值。

#coding=utf-8

def outer(fun):
def wrapper():
print (验证)

fun()

print (验证成功)
return wrapper

@outer
def func1():
print (‘func1‘)

@outer
def func2():
print (‘func2‘)

@outer
def func3():
print (‘func3‘)

@outer
def func4():
print (‘func4‘)


def before_func(request,kargs):
print (‘myname is before func,request is %s,kargs is %s‘%(request,kargs))

def main_func(request,kargs):
print (‘myname is main func,request is %s,kargs is %s‘%(request,kargs))


def after_func(request,kargs):
print (‘myname is after func,request is %s,kargs is %s‘%(request,kargs))


#装饰器的层层嵌套
def fiter(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


@fiter(before_func,after_func)
def test(request,args):
print (‘running...‘)

if __name__=="__main__":

# func1()
#
# func2()
#
# func3()
#
# func4()

s=test(‘hello‘,‘word‘)

print (s)

以上是关于python装饰器的主要内容,如果未能解决你的问题,请参考以下文章

python 装饰器:装饰器实例内置装饰器

python 装饰器:装饰器实例内置装饰器

python 装饰器:装饰器实例类装饰器(装饰函数)

python 装饰器:装饰器实例类装饰器(装饰函数)

理解Python装饰器

python高阶3 python装饰器