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/03 Report--
This article mainly explains "how to use the decorator". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Now let the editor take you to learn how to use the decorator.
1. Conventional decorator
The following is the simplest example of a decorator, printing a log before and after running the myfunc function.
Def deco (func): def wrapper (* args, * kw): print ("Ready to run task") func (* args, * * kw) print ("Successful to run task") return wrapper @ deco def myfunc (): print ("Running the task") myfunc ()
Decorator used, it seems that some high-end and magical, for some repetitive functions, we often encapsulate into a decorator function.
When defining a decorator, we all need to write a nested function mechanically as above. Beginners who do not have a deep understanding of the principle of the decorator will often forget how to define the decorator after a while.
Some smarter students will use PyCharm to automatically generate decorator templates.
Then, when you want to use it, typing deco directly will generate a simple generator code, which improves the efficiency of coding preparation.
two。 Use the shrine.
Using PyCharm's Live Template makes it easier to write decorators, but relies on PyCharm, a professional code editor.
Here, brother Ming wants to teach you a simpler method. To use this method, you need to install a library: decorator, which can be easily installed using pip.
$python3-m pip install decorator
It is not difficult to see from the name of the library that this is a third-party library dedicated to solving decorator problems.
With it, you will be surprised to find that decorators defined by yourself will no longer need to write nested functions.
From decorator import decorator @ decorator def deco (func, * args, * * kw): print ("Ready to run task") func (* args, * * kw) print ("Successful to run task") @ deco def myfunc (): print ("Running the task") myfunc ()
Deco as a decoration function, the first parameter is fixed, all refer to the decorated function, while the following parameters are always written with variable parameters * args and * * kw, and the code is decorated with the original parameters of the function.
This way of writing, I have to say, is more intuitive and the logic of the code is easier to understand.
3. Is the decorator with parameters available?
Decorators can be divided into two types according to whether they carry parameters or not.
The first one: the simplest example without parameters, which has been given above
Def decorator (func): def wrapper (* args, * * kw): func (* args, * * kw) return wrapper
The second kind: with parameters, which is relatively complex and not so easy to understand.
Def decorator (arg1, arg2): def wrapper (func): def deco (* args, * * kwargs) func (* args, * * kwargs) return deco return wrapper
So can decorator also support decorators that require parameters?
Here is an official example
From decorator import decorator @ decorator def warn_slow (func, timelimit=60, * args, * * kw): t0 = time.time () result = func (* args, * * kw) dt = time.time ()-t0 if dt > timelimit: logging.warn ('% s took% d seconds', func.__name__, dt) else: logging.info ('% s took% d seconds', func.__name__) Dt) return result @ warn_slow (timelimit=600) # warn if it takes more than 10 minutes def run_calculation (tempdir, outdir): pass
You can see:
The first argument to the decorator function is the decorated func, which is the same as before.
The second parameter, timelimit, is written as the position parameter, and has a default value.
After that, the variable parameter method is used as before.
It is not difficult to infer that as long as you start with the second argument in the decorator function and use the non-mutable argument, these parameters can be used as parameters when the decorator is called.
4. Has the signature problem been solved?
When we write our own decorators, we usually add a decorator called functools.wraps. I think you have seen it often, so what is the use of it?
Let's take a look at an example.
Def wrapper (func): def inner_function (): pass return inner_function @ wrapper def wrapped (): pass print (wrapped.__name__) # inner_function
Why is this happening? Shouldn't I return func?
This is not difficult to understand, because the upper execution func and the lower decorator (func) are equivalent, so the above func.__name__ is equivalent to the following decorator (func). _ _ name__, of course, the name is inner_function.
Def wrapper (func): def inner_function (): pass return inner_function def wrapped (): pass print (wrapper (wrapped). _ _ name__) # inner_function
Currently, we can see that when a function is decorated by a decorator, its signature information changes (such as the function name seen above).
So how to avoid this kind of situation?
The solution is to use what we mentioned earlier as the functools .compresps decorator.
Its function is to assign some attribute values of the modified function (wrapped) to the modifier function (wrapper), and finally make the display of attributes more in line with our intuition.
From functools import wraps def wrapper (func): @ wraps (func) def inner_function (): pass return inner_function @ wrapper def wrapped (): pass print (wrapped.__name__) # wrapped
So the question is, after we use decorator, will there still be this kind of signature problem?
Write an example to verify it.
From decorator import decorator @ decorator def deco (func, * args, * kw): print ("Ready to run task") func (* args, * * kw) print ("Successful to run task") @ deco def myfunc (): print ("Running the task") print (myfunc.__name__)
The output is myfunc, indicating that decorator has defaulted to help us deal with all foreseeable problems.
At this point, I believe you have a deeper understanding of "how to use the 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.