How to define python decorator
This article introduces the relevant knowledge of "how to define python decorator". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
Basic concept of decorator
Decorator function, as the name implies, is to decorate an object. In python
The decorator function decorates the object with the function and returns the decorated function. We often see that decorator functions are used with an @ symbol for convenience and simplicity. In essence, a decorator is a function, but a multi-layer nested function. Let me give you an example.
A simple example
We define the simplest decorator, decorate the functions passed in, and return the functions nested within the decorator.
The way you can understand the decoration.
# define a decorator function decorator
Def decorator (function):
Def inner ():
Print ('running inner ()')
Return inner
# the function target to be decorated
Def target ():
Print ('running target ()')
# decorator function begins to decorate the target function
Deco = decorator (target)
Deco ()
Return the result
Running inner ()
Analysis:
It is found that what is printed is not running target (), but running inner (), which indicates that the decorator function decorator decorates the target () function.
Call the decorator function using the @ symbol
The above method can be used, but it is not beautiful and simple. Used in python
@ + decorator function name A, and define the decorated function B below it, and then call the decorated function B
@ decorator
Def target ():
Print ('running target ()')
Target ()
Return the result
Running inner ()
Through the analysis, we can see that the two kinds of decorators are used in the same way.
This is the end of how to define the python decorator. Thank you for your reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!