Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the relevant knowledge points of Python decorator

2025-03-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly introduces "what are the relevant knowledge points of Python decorator". In daily operation, I believe many people have doubts about the relevant knowledge points of Python decorator. The editor consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful to answer the questions of "what are the relevant knowledge points of Python decorator?" Next, please follow the editor to study!

1. Decorator

Decorator: literally, it is the device that decorates the object. You can add new features or add restrictions or help output to the decorated object without modifying the original code.

The characteristic of the decorator is that the function appears as its parameter, and the decorator also has the characteristic of closure.

The sample code is as follows:

# define a 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 list") print ("students have been added to the class list") return wrapper@decoratedef student (): print ("I am a floret") student ()''- lose Give the result-I am Xiaohua has added students to the school student list, added students to the department student list and added students to the class list.

Decorate a function with a * * symbol plus a function name * *

Execution flow: because student is a decorated function, the system passes the student function as an argument to the decorate function (decorator decorate), executes the decorate function, and assigns the return value to the student function.

The previous code is equal to the following code:

# define a decorator def decorate (func): def wrapper (): func () print ("added students to the school student list") print ("added students to the department list") print ("added students to the class list") return wrapperdef student (): print ("I am a floret") # pass the return value to f and call F = decorate (student) # you cannot add () here Otherwise, it means calling f ()'- output results-I am Xiaohua who has added students to the school student list, added students to the department student list and added students to the class list.

If there is a directly executable statement outside the student function, it will also be executed without calling the student function

The sample code is as follows:

# define a decorator def decorate (func): print ("this is external code") def wrapper (): func () print ("added students to the school student list") print ("added students to the department list") print ("added students to the class list") return wrapper@decoratedef student (): print ("I am Floret ") # student ()'- output the result-this is the external code''1.1 application scenario

It can be used for e-commerce websites to determine whether users log in to continue execution; add logs and other scenarios

The sample code is as follows:

# define a 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 logged in") return wrapper@decorate # use decorator def add_shopping_cart (): print ("added successfully" ") @ decorate # use the decorator def payment (): print (" payment succeeded ") add_shopping_cart () payment ()''- output the result-adding successfully is verifying whether the user is logged in. Payment is successfully verifying that the user is logged in. Universal decorator

Because the parameters of the function may not be fixed, this can be done 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 of accepting any parameter print ("under detection.") Print (.) Print ("detected") func (* args, * * kwargs) return wrapper@decorate # uses the decorator def F1 (): # No parameter print ("this has no function") @ decoratedef f2 (name): # A parameter print ("name is:" Name) @ decoratedef student (* students): # multiple parameters # * students is used to receive multiple parameters for ch in students: print (ch) @ decoratedef student_classroom (* students) Classroom= "front-end class"): # receives the parameter print that can be assigned (f "this is the student of {classroom}") for ch in students: print (ch) # call function F1 ()'- output result-- is being tested. . After testing, this does not have any function''f2 ("one bowl week")''- output results-it is being tested. . After the test, the name is: a bowl of student ("Zhang San", "Li Si", "Wang Wu")'- output results-- is being tested. . After testing, Zhang San, Li Si, Wang Wu, student_classroom ("Zhang San", "Li Si", "Wang Wu", classroom= "front-end class")''is being tested. . After the test, this is Zhang San, Li Si, Wang Wu, a student from the front class.

To prevent errors, set the decorator as a universal decorator when you define it

3. Multi-layer decorator

The sequential execution order of multi-layer execution is from the inside to the outside, first calling the innermost decorator, and finally calling 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 learned math") return wrapperdef Chinese (func): # define the first decorator def wrapper (* args, * * kwargs): func (* args) * * kwargs) print ("the student has learned the language") return wrapperdef English (func): # define the third decorator def wrapper (* args, * * kwargs): func (* args) * * kwargs) print ("the student has learned English") return wrapper@maths@Englishdef student1 (name): print (f "student {name} has completed") @ English@Chinese@mathsdef student2 (name): print (f "student {name} has finished") # call function student1 ("Xiaoming") student Xiaoming has finished learning English The student has student2 maths the student Xiaohua has finished the student has studied maths the student has learned Chinese and the student has learned English Decorator with parameters

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

Layer 1: responsible for receiving the parameters of the decorator

The second layer: responsible for receiving functions

Layer 3: responsible for receiving the parameters of the function

The sample code is as follows:

# decorator with parameter def outer (a): # first layer: def decorate (func): # second layer: responsible for receiving function def wrapper (* args, * * kwargs): # layer 3 is responsible for receiving function parameter for i in range (a): print (I) func (* args) * * kwargs) return wrapper # returns: layer 3 return decorate # returns layer 2 @ outer (3) def number (): print ("printed") number () '012 finished printing''

The outermost function is responsible for receiving the decorator parameters, and the contents are still the contents of the original decorator.

At this point, the study of "what are the relevant knowledge points of Python decorator" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report