In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-04 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly explains "what is the use of Python decorator". Interested friends may wish to have a look at it. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn "what is the use of Python decorator"?
1. What is a decorator?
For encapsulated original functions such as f, the decorator can run some code before or after the f function is executed.
two。 The structure of the decorator
The decorator is also a function that decorates the original function f or class cls and then returns a function g
Decorate a function:
Def decorator (f): # defines the function to be returned def g (): print ('actions before function f execution') f () print ('actions after function f execution') return g
Decorate a class:
Def decorator (cls): # define the function def g (): print ('actions before class cls execution') f () print ('actions after class cls execution') return g
Using the decorator is simple, @ + custom decorator decorates the function you want to decorate.
3. Why are you doing this?
If you want to understand why the decorator has this structure, you must first understand what the decorator's goal is.
Its value is to add some behavior to the original function f, the premise must not destroy the function f, so certainly can not change the internal structure of f, so you can only define some behavior before and after calling f.
At the same time, what is the return value of the decorator function decorator? If you think about it, it couldn't be better to return a function that wraps the original function f.
4. Decorate a function
The printStar function receives a function f, and the return value is also a function, so it meets the structural requirements of the decorator, so printStar is a decorator.
Def printStar (f): def g (): print ('* * 20) f () print ('* * 20) return g
The printStar decorator prints 20 * characters before and after the f function is executed.
Use printStar:
@ printStar def f (): print ('hello world')
Call:
If _ _ name__ = ='_ _ main__': # change the function f ()
Print the results:
* hello world *
Other functions that can be easily decorated are as follows:
@ printStar def g (): print ('welcome to Python')
5. Decorate a class
In addition to decorating the function f, you can also decorate the class cls, both of which have the same principle.
The following is an example of a decorator implementing a singleton pattern, which means that a class has only one instance and cannot have a second.
Def singleton (cls): instance = {} def get_instance (* args, * * kwargs): if cls not in instance: instance [cls] = cls (* args, * * kwargs) return instance [cls] return get_instance
Define the dictionary instance, and the key-value pairs are class and instance, respectively, ensuring that you only cls () once.
Decorate the class with the decorator singleton:
@ singleton class CorePoint: pass
Test:
If _ _ name__ = ='_ main__': # change the function of the class C1 = CorePoint () c2 = CorePoint () print (C1 is c2) # True
6. Decorator cascading
The above original function f can be modified not only by one decorator, but also by n multiple decorators.
The following defines another decorator printLine, which prints 20 before and after the execution of the decorated function:
Def printLine (f): def g (): print ('-'* 20) f () print ('-'* 20) return g
Decorate the function f with the printStar and printLine defined above:
@ printStar @ printLine def f (): print ('hello world')
Call the function f again at this time:
If _ _ name__ = ='_ _ main__': # change function f ()
Print the results:
*-hello world-*
F after being decorated, print * first, and then print-
With one more layer of cascading, the original function f becomes more powerful. By using the decorator, the function can be extracted and the loose coupling can be further realized.
7. Warm reminder
Print the name of the original function f _ _ name__, and the result is f
In [1]: def f ():...: pass In [4]: F. roomnames _ Out [4]:'f'
However, after being decorated, the function name f becomes g, which is not what we want!
@ printStar def f (): pass f () f.roomname _ # g
Solution provided by Python: use the wraps decorator in the functools module:
From functools import wraps def printStar (f): @ wraps (f) def g (): print ('* * 20) f () print ('* * 20) return g
At this time, print the name of the decorated f, show f, normal!
At this point, I believe you have a deeper understanding of "what is the use of Python decorator". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
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.