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
The sidebar is recommended
- Python notes (6): definition and use of lists
- Python notes (V): string operation
- Python notes (IV): use of functions and modules
- Python notes (3): conditional statements and circular statements
- Python notes (II): lexical structure
- Notes on python (I): getting to know Python
- [Python data structure series] - tree and binary tree - basic knowledge - knowledge point explanation + code implementation
- [Python daily homework] Day7: how to combine two dictionaries in an expression?
- How to implement a custom list or dictionary in Python
- 15 advanced Python tips for experienced programmers
guess what you like
-
Python string method tutorial - how to use the find() and replace() functions on Python strings
-
Python computer network basics
-
Python crawler series: crawling global airport information
-
Python crawler series: crawling global port information
-
How to calculate unique values using pandas groupby
-
Application of built-in distribution of Monte Carlo simulation SciPy with Python
-
Gradient lifting method and its implementation in Python
-
Pandas: how to group and calculate by index
-
Can you create an empty pandas data frame and fill it in?
-
Python basic exercises teaching! can't? (practice makes perfect)
Random recommended
- Exploratory data analysis (EDA) in Python using SQL and Seaborn (SNS).
- Turn audio into shareable video with Python and ffmpeg
- Using rbind in python (equivalent to R)
- Pandas: how to create an empty data frame with column names
- Talk about quantifying investment using Python
- Python, image restoration in opencv - CV2 inpaint
- Python notes (14): advanced technologies such as object-oriented programming
- Python notes (13): operations such as object-oriented programming
- Python notes (12): inheritance such as object-oriented programming
- Chapter 2: Fundamentals of python-5 Boolean
- Python notes (11): encapsulation such as object-oriented programming
- Python notes (10): concepts such as object-oriented programming
- Gradient lifting method and its implementation in Python
- Van * Python | simple crawling of a site course
- Chapter 1 preliminary knowledge of pandas (list derivation and conditional assignment, anonymous function and map method, zip object and enumerate method, NP basis)
- Nanny tutorial! Build VIM into an IDE (Python)
- Fourier transform of Python OpenCV image processing, lesson 52
- Introduction to python (III) network request and analysis
- China Merchants Bank credit card number recognition project (Part I), python OpenCV image processing journey, Part 53
- Introduction to python (IV) dynamic web page analysis and capture
- Python practice - capture 58 rental information and store it in MySQL database
- leetcode 119. Pascal's Triangle II(python)
- leetcode 31. Next Permutation(python)
- [algorithm learning] 807 Maintain the city skyline (Java / C / C + + / Python / go / trust)
- The rich woman's best friend asked me to write her a Taobao double 11 rush purchase script in Python, which can only be arranged
- Glom module of Python data analysis module (1)
- Python crawler actual combat, requests module, python realizes the full set of skin to capture the glory of the king
- Summarize some common mistakes of novices in Python development
- Python libraries you may not know
- [Python crawler] detailed explanation of selenium from introduction to actual combat [2]
- This is what you should do to quickly create a list in Python
- On the 55th day of the journey, python opencv perspective transformation front knowledge contour coordinate points
- Python OpenCV image area contour mark, which can be used to frame various small notes
- How to set up an asgi Django application with Postgres, nginx and uvicorn on Ubuntu 20.04
- Initial Python tuple
- Introduction to Python urllib module
- Advanced Python Basics: from functions to advanced magic methods
- Python Foundation: data structure summary
- Python Basics: from variables to exception handling
- Python notes (22): time module and calendar module