如何理解 Python 装饰器(2)

def decorate02(fun1):
    def wapper(*args,**kwargs):
        print ('I am decorate02')
        fun1(*args,**kwargs)
        print('nice to meet you')
    return wapper

@decorate01
@decorate02
def show(*args,**kwargs):
    print (args[0])
    print (args[1])
    print (args[2])

show('Mr Alice','Mr Tim','Mr tu')

# 执行结果:

hello world
I am decorate02
Mr Alice
Mr Tim
Mr tu
nice to meet you
I am decorate01

装饰器功能扩展

#!/usr/local/python27/bin/python2.7

def before(request,*args,**kwargs):
    print('before')

def after(request,*args,**kwargs):
    print('after')

def Filter(before_func,after_func):
    def outer(fun1):
        def wapper(request,*args,**kwargs):

before_result = before_func(request,*args,**kwargs)
            if(before_result != None):
                return before_result;

fun1_result = fun1(request,*args,**kwargs)
            if(fun1_result != None):
                return fun1_result;

after_result = after_func(request,*args,**kwargs)
            if(after_result != None):
                return after_result;

return wapper
    return outer

@Filter(before,after)
def show(request,*args,**kwargs):
    print ('Mr tu')


show('1')

# 执行结果:

before
Mr tu
after

函数若未定义返回值,执行成功返回值默认为 None ,这里的语句 if (before_result != None) 意思就是before函数执行失败时采取什么操作。

Linux公社的RSS地址https://www.linuxidc.com/rssFeed.aspx

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/bcc328fd8e05f014d0cf27a4d0894b25.html