Python3 decorator

decorator

    Definition: The essence is a function, decorating other functions (that is, adding additional functions to other functions)

    Principle: 1. The source code of the decorated function cannot be modified

              2. The calling method of the decorated function cannot be modified

Knowledge reserves for implementing decorators : 1. Functions are "variables" 2. Higher-order functions 3. Nested functions (use def to declare a new function in a function body)

Higher-order functions + nested functions -- "decorators"


Memory recycling mechanism : The memory recycling mechanism for variables and functions is the same

Examples are as follows:

def timer(func):
    def deco():
        func()
        print(3)
    return deco
@timer # ---> test1 = timer (test1)
def test1():
    print(1)

@timer
def test2():
    print(2)

test1()
test2 ()
output:
1
3
2
3

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324609081&siteId=291194637