current position:Home>Python notes (18): decorator

Python notes (18): decorator

2022-01-30 15:41:17 A bowl week

Little knowledge , Great challenge ! This article is participating in “ A programmer must have a little knowledge ” Creative activities .

Hello everyone , I am a A bowl week , One doesn't want to be drunk ( Internal volume ) The front end of the . If you are lucky enough to get your favor , I'm very lucky ~

Decorator

Decorator (Decorator): Literally , It's the device that decorates the object . You can do this without changing the original code , Add new functions or add restrictions or help output to the decorated objects .

The feature of decorator is that the function appears as its parameter , Decorators also feature closures . The sample code is as follows :

#  Define a decorator 
def decorate(func):
    def wrapper():
        func()
        print(" Students have been added to the school's student list ")
        print(" Students have been added to the Department's student list ")
        print(" Students have been added to the class list ")

    return wrapper


@decorate
def student():
    print(" I'm Xiaohua ")


student()
'''
--- Output results ---
 I'm Xiaohua 
 Students have been added to the school's student list 
 Students have been added to the Department's student list 
 Students have been added to the class list 
'''
 Copy code 

Use **@**** Sign plus function name ** To decorate a function

Execute the process : because student It's a decorated function , The system will student Function is passed in as an argument decorate function ( Decorator decorate), perform decorate function , And assign the return value to student function .

The previous code is equal to the following code :

#  Define a decorator 
def decorate(func):
    def wrapper():
        func()
        print(" Students have been added to the school's student list ")
        print(" Students have been added to the Department's student list ")
        print(" Students have been added to the class list ")

    return wrapper


def student():
    print(" I'm Xiaohua ")


#  Pass the return value to f  And call 
f = decorate(student)  #  You can't add it here (), Otherwise, it means calling 
f()
'''
--- Output results ---
 I'm Xiaohua 
 Students have been added to the school's student list 
 Students have been added to the Department's student list 
 Students have been added to the class list 
'''
 Copy code 

If student There are directly executable statements outside the function , Don't call student In the case of functions , It will also be carried out , The sample code is as follows :

#  Define a decorator 
def decorate(func):
    print(" This is external code ")

    def wrapper():
        func()
        print(" Students have been added to the school's student list ")
        print(" Students have been added to the Department's student list ")
        print(" Students have been added to the class list ")

    return wrapper


@decorate
def student():
    print(" I'm Xiaohua ")


# student()
'''
--- Output results ---
 This is external code 
'''
 Copy code 

Application scenarios

It can be used for e-commerce website to judge whether the user logs in to continue execution ; Add scenarios such as logs , The sample code is as follows :

#  Define a decorator 
def decorate(func):
    def wrapper():
        func()
        print(" Verifying that the user is logged in ")
        # if  #  Code block to determine whether to log in 
        #     pass
        print(" User logged in ")

    return wrapper


@decorate  #  Use decorators 
def add_shopping_cart():
    print(" Add success ")


@decorate  #  Use decorators 
def payment():
    print(" Payment succeeded ")


add_shopping_cart()
payment()

'''
--- Output results ---
 Add success 
 Verifying that the user is logged in 
 User logged in 
 Payment succeeded 
 Verifying that the user is logged in 
 User logged in 
'''
 Copy code 

Universal decorator

Because the parameters of the function may not be fixed , Therefore, this function can be completed through the variable parameters of the function .

The sample code is as follows :

def decorate(func):
    def wrapper(*args, **kwargs):  #  Use variable parameters to achieve the effect that any parameter can be accepted 
        print(" In the process of testing ...")
        print(".............")
        print(" detection complete ")
        func(*args, **kwargs)

    return wrapper


@decorate  #  Use decorators 
def f1():  #  No parameter 
    print(" This doesn't have any function ")


@decorate
def f2(name):  #  One parameter 
    print(" The name is :", name)


@decorate
def student(*students):  #  Multiple parameters   # *students Used to receive multiple parameters 
    for ch in students:
        print(ch)


@decorate
def student_classroom(*students, classroom=" Front end shift "):  #  Receive parameters that can be assigned 
    print(f" This is a {classroom} Of the students ")
    for ch in students:
        print(ch)


#  Call function 
f1()
'''
--- Output results ---
 In the process of testing ...
.............
 detection complete 
 This doesn't have any function 
'''
f2(" A bowl week ")
'''
--- Output results ---
 In the process of testing ...
.............
 detection complete 
 The name is :  A bowl week 
'''
student(" Zhang San ", " Li Si ", " Wang Wu ")
'''
--- Output results ---
 In the process of testing ...
.............
 detection complete 
 Zhang San 
 Li Si 
 Wang Wu 
'''
student_classroom(" Zhang San ", " Li Si ", " Wang Wu ", classroom=" Front end shift ")
'''
 In the process of testing ...
.............
 detection complete 
 This is the student in the front class 
 Zhang San 
 Li Si 
 Wang Wu 
'''
 Copy code 

To prevent mistakes , When defining a decorator, set it as a universal decorator

Multi layer decorator

The multi-layer execution sequence is from the inside to the outside , First call the innermost decorator , Finally, call the outermost decorator , The sample code is as follows :

def maths(func):  #  Define the first decorator 
    def wrapper(*args, **kwargs):
        func(*args, **kwargs)
        print(" The student has studied mathematics ")

    return wrapper


def Chinese(func):  #  Define the second decorator 
    def wrapper(*args, **kwargs):
        func(*args, **kwargs)
        print(" The student has learned Chinese ")

    return wrapper


def English(func):  #  Define the third decorator 
    def wrapper(*args, **kwargs):
        func(*args, **kwargs)
        print(" The student has learned English ")

    return wrapper


@maths
@English
def student1(name):
    print(f" Student {name} It's done ")


@English
@Chinese
@maths
def student2(name):
    print(f" Student {name} It's done ")


#  Call function 
student1(" Xiao Ming ")
'''
 Student Xiao Ming has finished 
 The student has learned English 
 The student has studied mathematics 
'''
student2(" floret ")
'''
 Student Xiaohua has finished 
 The student has studied mathematics 
 The student has learned Chinese 
 The student has learned English 
'''
 Copy code 

Parameter decorator

The decorator with parameters is divided into three layers , They are as follows :

first floor : Be responsible for receiving the parameters of the decorator

The second floor : Responsible for receiving functions

The third level : Responsible for receiving the parameters of the function

The sample code is as follows :

#  Decorator with parameters 
def outer(a):  #  first floor :  Be responsible for receiving the parameters of the decorator 

    def decorate(func):  #  The second floor  :  Responsible for receiving functions 

        def wrapper(*args, **kwargs):  #  The third level     Responsible for receiving the parameters of the function 
            for i in range(a):
                print(i)
            func(*args, **kwargs)

        return wrapper  #  What comes back is : The third level 

    return decorate  #  What comes back is : The second floor 


@outer(3)
def number():
    print(" Print complete ")


number()
'''
0
1
2
 Print complete 
'''
 Copy code 

The outermost function is responsible for receiving decorator parameters , The content inside is the content of the original ornament .

copyright notice
author[A bowl week],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/01/202201301541142752.html

Random recommended