The true meaning and usage of decorators in python

Closure:

Closure is a very practical way of writing in python, which allows users to call variables of functions outside the function in the function, making the variable resident in memory.

Closure function:

The input is a function, and the output is also a function.

The way decorators are written is syntactic sugar for python closures.

Call result questions that are often interviewed in interviews:

# ---encoding:utf-8---
# @Author  : CBAiotAigc
# @Email   :[email protected]
# @Site    : 
# @File    : 两个装饰器.py
# @Project : PythonUtils
# @Software: PyCharm
def wrapper1(func):
    print("set wrapper1")

    def inner_wrapper1(*args, **kwargs):
        print("进入inner_wrapper1")
        ret = func(*args, **kwargs)
        print("离开inner_wrapper1")
        return ret

    return inner_wrapper1


def wrapper2(func):
    print("set wrapper2")

    def inner_wrapper2(*args, **kwargs):
        print("进入inner_wrapper2")
        ret = func(*args, **kwargs)
        print("离开inner_wrapper2")
        return ret

    return inner_wrapper2


@wrapper1
@wrapper2
def func():
    print("func 函数调用")


if __name__ == '__main__':
    func()

The decorator enhances the first time the decorated function is called

  • Enhancement timing? before the first call to
  • Number of enhancements? enhance only once

Call logic analysis of the above code:

func = wrapper2(func)
func = wrapper1(func)

func()

Guess you like

Origin blog.csdn.net/wtl1992/article/details/132142178