当前位置:网站首页>Multiple decorators decorate a function

Multiple decorators decorate a function

2022-06-25 16:10:00 creedcc

# !/usr/bin/env python
# -*- coding:utf-8 -*-

def wrapper1(func1):  # func1 == func Primitive function 
    def inner1(*args, **kwargs):
        print('wrapper1, before func')
        ret1 = func1(*args, **kwargs)
        print('wrapper1, after func')
        return ret1
    return inner1


def wrapper2(func2):  # func2 = inner1
    def inner2(*args, **kwargs):
        print('wrapper2, before func')
        ret2 = func2(*args, **kwargs)
        print('wrapper2, after func')
        return ret2
    return inner2


@wrapper2     #  The second step : func = wrapper2(func),  Before executing the decorator, follow the first step func==inner1,  Actuator finisher wrapper2 after ,func2==inner1, Sinister func==inner2
@wrapper1     #  First step : func = wrapper1(func),  Actuator finisher wrapper1, be func1 == func,  Sinister  func==inner1
def func():
    print("Hello World!")


func()    #  The third step : func() == inner2() , Then execute the functions in turn according to the call  , ( According to the second step :func==inner2)


The execution sequence is shown in the figure :
 Insert picture description here

原网站

版权声明
本文为[creedcc]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202190535405679.html