python core -- the use of decorator

Keywords: Python

Concept of decorator

Decorator is a function often used in the process of program development. If you use decorator well, the development efficiency will be enhanced

Function of decorator

Introduce the functions of log, function execution time statistics, function preparation before execution, function cleaning after execution, authority verification, etc

The premise of learning ornament

To learn decorators well, we need to know what is closure

The concept of closure

Another function is defined inside the function, and the function uses the variables of the external function. Then the function and some variables used are called closures

Definition of closure

def line_conf(a, b):
    def line(x):
        return a*x + b
    return line

line1 = line_conf(1, 1)
print(line1(5))

When the function executes line conf, it returns the address of an inner function. We use Line1 to receive the returned value of line conf, and then we call line1() function, which is equivalent to calling the inner line() function, which is a closure

Decorator execution process

Execution principle of decorator

# This is a closure
def w1(fun):
    def inner():
        fun() # Point to f1 function
    return inner
# This is a normal function
def f1():
    print("This is f1 function")
# Return value of w1 to f1
f1 = w1(f1)
# This function actually performs the inner() function
f1()

Definition of decorator

def w1(fun):
        def inner():
            fun() # Point to f1 function
        return inner
@w1
def f1():
    print("This is f1 function")
# It actually points to the inner function
f1()

When the same function is decorated by two decorators

If a function is decorated by two decorator functions, the execution process is from top to bottom, but the actual decoration process is from bottom to top

# Define function to complete package data
def makeBold(fun):
    print("Decorating 1")
    def wrapped():
        print("---1---")
        return "<b>" + fun() + "</b>"
    return wrapped

#Define function to complete package data
def makeItalic(fun):
    print("Decorating 2")
    def wrapped():
        print("---2---")
        return "<i>" + fun() + "</i>"
    return wrapped

# Decorating
@makeBold    # Equivalent to text3 = makeBold(text2)
@makeItalic  # Equivalent to text2 = nameItalic(text3)
def text3():
    print("---3---")
    return "hello world!"

# Print results
ret = text3()
print(ret)

The result is

Classification of decorators

Decorate functions without parameters and return values

def fun(functionName):
    def fun_in():
        print("This is fun_in function")
        functionName()
    return fun_in
@fun
def f1():
    print("This is f1 function!")
f1()

Function decorated with parameters and no return value

def fun(functionName):
    def fun_in(*args, **kwargs):
        print("This is fun_in function")
        functionName(*args, **kwargs))
    return fun_in
@fun
def f1(a, b):
    print("%s%s" %(a, b))
f1(1, 2)

Decorate a function with no parameters and return values

def fun(functionName):
    def fun_in():
        print("This is fun_in function")
        ret = functionName()
    return fun_in
@fun
def f1():
    return "hello python!"
ret = f1() # Point to the fun in function
print(ret)

Functions decorated with parameters and return values (Universal decorator)

def fun(functionName):
    def fun_in(*args, **kwargs):
        print("This is fun_in function")
        ret = functionName(*args, **kwargs))
    return fun_in
@fun
def f1(a, b):
    return a + b
ret = f1(1, 2)
print(ret)

Decorator with parameters

Function of decorator with parameters: it can play different roles in the process of operation

# It needs a three-layer function to realize
def fun_arg(arg):
    def fun(functionName):
        def fun_in():
            print("The parameters of the decorator are:%s" %(arg))
            functionName()
        return fun_in
return fun

@fun_arg("ha ha ha") # Decorator with parameters
def text():
    print("---text---")
text()

Posted by tomm098 on Fri, 03 Apr 2020 22:11:53 -0700