In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly introduces "how to define Python decorator". In daily operation, I believe many people have doubts about how to define 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 doubts of "how to define Python decorator". Next, please follow the editor to study!
Decorator is an advanced Python syntax. The decorator can process a function, method, or class. In Python, there are many ways to process functions and classes. For example, in the Python closure, we see the return result of the function object as a function. Compared with other ways, the decorator has simple syntax and high readability of the code. Therefore, decorators are widely used in Python projects.
Decorators first appeared in Python 2.5 and were originally used to process callable objects such as functions and methods (callable object, which are defined with the _ _ call__ method). In Python 2.6 and later versions of Python, decorators are further used for processing classes.
Decorative functions and methods
Let's first define two simple mathematical functions, one to calculate the sum of squares and the other to calculate the square difference:
# get square sumdef square_sum (a, b): return astatine 2 + breadbasket get square diffdef square_diff (a, b): return astatine 2-b**2print (square_sum (3,4)) print (square_diff (3,4))
After having the basic mathematical functions, we may want to add other functions to the function, such as printout. We can rewrite the function to do this:
# modify: print input# get square sumdef square_sum (a, b): print ("intput:", a, b) return astatine 2 + baked cake get square diffdef square_diff (a, b): print ("input", a, b) return astatine 2-b**2print (square_sum (3,4)) print (square_diff (3,4))
We modified the definition of the function to add function.
Now, we use the decorator to make the above changes:
Def decorator (F): def new_F (a, b): print ("input", a, b) return F (a, b) return new_F# get square sum@decoratordef square_sum (a, b): return astatine 2 + baked cake get square diff@decoratordef square_diff (a, b): return astatine 2-b**2print (square_sum (3,4)) print (square_diff (3,4))
Decorators can be defined in the form of def, such as decorator in the above code. The decorator takes a callable object as an input parameter and returns a new callable object. The decorator creates a new callable object, which is the new_F above. In new_F, we add the function of printing, and realize the function of the original function by calling F (a, b).
Once the decorator is defined, we can use the @ syntax. By calling @ decorator before the functions square_sum and square_diff are defined, we actually pass square_sum or square_diff to decorator and assign the new callable object returned by decorator to the original function name (square_sum or square_diff). So, when we call square_sum (3,4), it is equivalent to:
Square_sum = decorator (square_sum) square_sum (3,4)
We know that variable names and objects in Python are separate. The variable name can point to any object. In essence, the decorator plays the role of re-pointing to the variable name (name binding), so that the same variable name points to a newly returned callable object, thus achieving the purpose of modifying the callable object.
Similar to the processing function, we can use the decorator to process the class.
If we have other similar functions, we can continue to call decorator to decorate the function without repeatedly modifying the function or adding a new wrapper. In this way, we improve the reusability of the program and increase the readability of the program.
Decorator with parameters
In the above decorator call, such as @ decorator, the decorator defaults to the function that follows it as the only argument. The decorator's syntax allows us to provide other parameters, such as @ decorator (a), when we call decorator. In this way, it provides more flexibility for the writing and use of the decorator.
# a new wrapper layerdef pre_str (pre=''): # old decorator def decorator (F): def new_F (a, b): print (pre + "input", a, b) return F (a, b) return new_F return decorator# get square sum@pre_str ('^ _ ^') def square_sum (a B): return astatine 2 + baked get square diff@pre_str ('Tubt') def square_diff (a, b): return astatine 2-b**2print (square_sum (3,4)) print (square_diff (3,4))
The pre_str above is a decorator that allows parameters. It is actually a function encapsulation of the original decorator and returns a decorator. We can think of it as a closure with environmental parameters. When we use the @ pre_str ('^ _ ^') call, Python can discover this layer of encapsulation and pass parameters to the decorator's environment. This call is equivalent to:
Square_sum = pre_str ('^ _ ^') (square_sum) Decoration Class
In the above example, the decorator receives a function and returns a function, thus acting as a processing function. Since Python 2. 6, decorators have been extended to classes. A decorator can receive a class and return a class, thus having the effect of processing a class.
Def decorator (aClass): class newClass: def _ init__ (self, age): self.total_display = 0 self.wrapped = aClass (age) def display (self): self.total_display + = 1 print ("total display", self.total_display) self.wrapped.display () return newClass@decoratorclass Bird: def _ init__ (self Age): self.age = age def display (self): print ("My age is", self.age) eagleLord = Bird (5) for i in range (3): eagleLord.display ()
In decorator, we return a new class, newClass. In the new class, we record the object (self.wrapped) generated by the original class and attach a new property, total_display, to record the number of calls to display. We also changed the display method.
With modification, our Bird class can show the number of times display is called.
At this point, the study on "how to define 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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.