Python Decorator Details
- 2021-12-12 05:04:07
- OfStack
1. Decorator
Decorator (
Decorator
): Literally, it is a device that decorates an object. You can add new functions to the decorated object or attach restrictions or help output without modifying the original code.
The feature of the decorator is that the function appears as its parameter, and the decorator also has the feature of closure.
The sample code looks like this:
# Definition 1 Decorator
def decorate(func):
def wrapper():
func()
print(" Students have been added to the school student list ")
print(" Students have been added to the department student list ")
print(" Students have been added to the class list ")
return wrapper
@decorate
def student():
print(" I'm a little flower ")
student()
'''
--- Output result ---
I'm a little flower
Students have been added to the school student list
Students have been added to the department student list
Students have been added to the class list
'''
Use **
@
**** Symbol plus function name ** to decorate 1 function
Execution process: because
student
Is the decorated function, and the system will
student
Function is passed in the form of parameters
decorate
Function (decorator
decorate
), execution
decorate
Function and assign the return value to the
student
Function.
The last 1 code is equal to the following 1 code:
# Definition 1 Decorator
def decorate(func):
def wrapper():
func()
print(" Students have been added to the school student list ")
print(" Students have been added to the department student list ")
print(" Students have been added to the class list ")
return wrapper
def student():
print(" I'm a little flower ")
# Pass the return value to the f And call the
f = decorate(student) # You can't add it here () Otherwise, it means calling the
f()
'''
--- Output result ---
I'm a little flower
Students have been added to the school student list
Students have been added to the department student list
Students have been added to the class list
'''
If
student
There are directly executable statements outside the function, and they are not called
student
Function is also executed,
The sample code is as follows:
# Definition 1 Decorator
def decorate(func):
print(" This is external code ")
def wrapper():
func()
print(" Students have been added to the school student list ")
print(" Students have been added to the department student list ")
print(" Students have been added to the class list ")
return wrapper
@decorate
def student():
print(" I'm a little flower ")
# student()
'''
--- Output result ---
This is external code
'''
1.1 Application Scenarios
It can be used for judging whether the user logs in to continue the execution of the e-commerce website; Add logs and other scenarios,
The sample code looks like this:
# Definition 1 Decorator
def decorate(func):
def wrapper():
func()
print(" Verifying whether the user is logged in ")
# if # Code block to determine whether to log in
# pass
print(" User is logged in ")
return wrapper
@decorate # Use decorators
def add_shopping_cart():
print(" Successful addition ")
@decorate # Use decorators
def payment():
print(" Payment Successful ")
add_shopping_cart()
payment()
'''
--- Output result ---
Successful addition
Verifying whether the user is logged in
User is logged in
Payment Successful
Verifying whether the user is logged in
User is logged in
'''
2. Universal decorator
Because the parameters of a function may not be fixed, this function can be accomplished by 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 of accepting any parameters
print(" It is being tested. . . ")
print(".............")
print(" Finished testing ")
func(*args, **kwargs)
return wrapper
@decorate # Use decorators
def f1(): # Parametric-free
print(" This one doesn't have any function ")
@decorate
def f2(name): # 1 Parameters
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 {classroom} Students of ")
for ch in students:
print(ch)
# Call function
f1()
'''
--- Output result ---
It is being tested. . .
.............
Finished testing
This one doesn't have any function
'''
f2("1 Bowl week ")
'''
--- Output result ---
It is being tested. . .
.............
Finished testing
The name is: 1 Bowl week
'''
student(" Zhang 3", " Li 4", " Wang 5")
'''
--- Output result ---
It is being tested. . .
.............
Finished testing
Zhang 3
Li 4
Wang 5
'''
student_classroom(" Zhang 3", " Li 4", " Wang 5", classroom=" Front-end shift ")
'''
It is being tested. . .
.............
Finished testing
This is the front class student
Zhang 3
Li 4
Wang 5
'''
To prevent errors, set the decorator as a universal decorator when defining it
3. Multi-layer decorator
The execution sequence of multi-layer is from inside to outside, the innermost decorator is called first, and the outermost decorator is called last.
The sample code looks like this:
def maths(func): # Definition section 1 Decorator
def wrapper(*args, **kwargs):
func(*args, **kwargs)
print(" The student has studied mathematics ")
return wrapper
def Chinese(func): # Define the first decorator
def wrapper(*args, **kwargs):
func(*args, **kwargs)
print(" The student has learned Chinese ")
return wrapper
def English(func): # Definition section 3 Decorator
def wrapper(*args, **kwargs):
func(*args, **kwargs)
print(" The student has learned English ")
return wrapper
@maths
@English
def student1(name):
print(f" Students {name} It has been completed ")
@English
@Chinese
@maths
def student2(name):
print(f" Students {name} It has been completed ")
# Call function
student1(" Xiao Ming ")
'''
Student Xiaoming has finished it
The student has learned English
The student has studied mathematics
'''
student2(" Floret ")
'''
Student floret has finished
The student has studied mathematics
The student has learned Chinese
The student has learned English
'''
4. Decorator with parameters
Decorator 1 with parameters is divided into three layers, as follows:
Layer 1: Responsible for receiving the parameters of the decorator Layer 2: Responsible for receiving functions Layer 3: Responsible for receiving the parameters of the functionThe sample code looks like this:
# Decorator with parameters
def outer(a): # No. 1 1 Layers: Responsible for receiving the parameters of the decorator
def decorate(func): # No. 1 2 Layer : Responsible for receiving function
def wrapper(*args, **kwargs): # No. 1 3 Layer 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 first 3 Layer
return decorate # What comes back is: the first 2 Layer
@outer(3)
def number():
print(" Print finished ")
number()
'''
0
1
2
Print finished
'''
The outermost function is responsible for receiving decorator parameters, and the contents inside are still the contents of the original decorator.