Python教程

python多个装饰器嵌套

本文主要是介绍python多个装饰器嵌套,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
#_*_ encoding: utf-8 _*_
def wrapper1(f1):
    # print('in wrapper1')
    def inner1(*args,**kwargs):
        print('in inner1')
        ret = f1(*args,**kwargs)
        print('111')
        return ret
    return inner1

def wrapper2(f2):
    # print('in wrapper2')
    def inner2(*args,**kwargs):
        print('in inner2')
        ret = f2(*args,**kwargs)
        print('222')
        return ret
    return inner2

def wrapper3(f3):
    # print('in wrapper3')
    def inner3(*args,**kwargs):
        print('in inner3')
        ret = f3(*args,**kwargs)
        print('333')
        return ret
    return inner3

@wrapper1  #3 func = wrapper1(func) func = wrapper2(inner2) -->f1 = inner2 -->print    in wrapper1 --> func = inner1
@wrapper2  #2 func = wrapper2(func) func = wrapper2(inner3) -->f2 = inner3 --> print  in wrapper2 --> func = inner2
@wrapper3  #1 func = wrapper3(func) --> f3 = func -->print in wrapper3 --> func = inner3
def func():   # first
    print('in func')

func() #4 func = inner1

输出:

in inner1
in inner2
in inner3
in func
333
222
111
这篇关于python多个装饰器嵌套的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!