Some understanding of function decorators

In python, we often hear\ see a class of function A, and there is a mark similar to @xxx before the definition declaration (def) of this type of function. For this type of function A, we call it the modified function, and for xxx in @ we call it a function decorator. (Some places are translated as function decorators )
This is what I saw in the articles of other bloggers. It is more vivid, so I will borrow it. Function decorator is a relatively useful technique, but it is easily overlooked by many people, and it is not mentioned in some tutorials. In fact, it is not difficult, it can maximize the utilization of existing programs, and only need to change the input or output part of the function to realize some functions that the original function does not have.
Specific code:

def old_func(func):
    print('我是old_func,我被执行了')
    def mid_func(name):
        print('我是mid_func,我被执行了')
        func(name)
        print('我是mid_func,我又被执行了')
        return None
    return mid_func
# 这里使用修饰器来实现新的函数功能
# 其实等价于: old_func(new_func(name))
@old_func
def new_func(name):
    print('我是{},我被执行了'.format(name))

new_func('被修饰的函数')

The output is:

我是old_func,我被执行了
我是mid_func,我被执行了
我是被修饰的函数,我被执行了
我是mid_func,我又被执行了

The principle is actually because the parameters passed in by functions in python can not only be general types or other reference types of data, but also the function itself. After all, in python, "everything can be an object". After understanding this, you can compare It's good to understand this. Of course, it's a bit like function inheritance.

Guess you like

Origin blog.csdn.net/onepunch_k/article/details/123991066