In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-03 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly introduces "what are the basic functions of the decorator in Python". In the daily operation, I believe that many people have doubts about the basic functions of the decorator in Python. The editor consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful for you to answer the question of "what are the basic functions of the decorator in Python?" Next, please follow the editor to study!
Preface
In python, because the decorator is a feature inherent in the python language, it is strange for its implementation and its usage. Here I record my understanding of it to deepen my impression.
What is a decorator?
As to what a decorator is, we should actually know why there is a decorator.
Decorator is a very interesting feature introduced by python. It is mainly used to solve the problem that you want to extend the function on the basis of the original function or class, but it will not destroy the function itself. And we can easily add and remove the requirements of this part of the extended function.
For example, when you are debugging code, you want to add print debugging information to some functions. However, this feature is only used when we are debugging and is not needed for official release. If you modify inside the function at this time, because there are multiple functions that need to add the same or similar information, then you need to modify one by one, which is a bit troublesome, at this time we can use the decorator to solve this problem.
Before explaining how to use decorators, we need to talk about the basic concepts related to decorators.
The basic characteristics of Python function
The nature of the function name:
In python, everything is an object, that is, the variables and functions we define are one object. Instead, the object means that we can get the properties of the object, for example, the function object has a property of _ _ name__:
Def function (): # define a function print ('this is a function!') function () print (function) # print the address of the function name print (function.__name__) # print the function name a = function # assign the function to a variable a () print (a) # print the address of a (a) print (a) # print the function name again
Print the results:
This is a function!
Function
This is a function!
Function
As can be seen from the print, when our function name is assigned to another variable, the function address and the function name in the function property do not change. In other words, when we define a function, our function name is the same as an ordinary variable, except that our function name points to a memory space in which the contents of a function body are stored.
However, when we assign this function name to another variable, the function name assigns the address of the memory space it executes to another variable, so the other variable becomes a function.
We have noticed here that if the function name is not added (), then it is the same as an ordinary variable, and after adding (), it will execute the contents of our function.
Here we will try to delete the function name we used when defining:
Del function # Delete the function function a () # execute a () print (a) # print out the address that a points to, print (a.printer _) # print the function name function () print (function) print (function.__name__) of a
View printing:
This is a function!
Function
NameError: name 'function' is not defined
As you can see, our function () function name hint is not defined, but our a () function can be printed normally. The del here actually deletes the pointer to the function name of our function, which points to the function address, and then it becomes a real undefined variable.
Use a function as a variable:
Since function names and ordinary variables can be assigned to each other, it means that we can also use function names in the same way as ordinary variables.
Define a function in a function:
We can define one function in the same way as a normal variable:
Def function1 (): print ('this is function1') def function2 (): print ('this is function2!') Return 0 function2 () return 0function1 () function2 ()
Print as follows:
This is function 1
This is function 2!
NameError: name 'function2' is not defined
As you can see, we defined a function2 function in function1 and used the function2 function in function1. However, when we use the function2 function outside, we print that the function is undefined. It is shown here that the scope of the function defined within the function is limited to the interior of the function, which is the same as our local variables.
However, this is not the case when we take a function as a return value. Refer to my previous article: variable scope in closures in Python
Returns the function name in a function:
Now that we can define another function in one function, we can return another function in the function:
Def function1 (): print ('this is function1') def function2 (): print ('this is function2!') Return 0 function2 () # use the function return function2 # inside the function to return the function name a = function1 () # to a variable a ()
Print as follows:
This is function 1
This is function 2!
This is function 2!
As you can see here, ours defines and returns the function function2 in the function function1 and uses a variable outside to receive the return value of funciton1. From this, we can see that there is little difference between the use of function names and variables.
Note: although we say that we return another function in one function, in fact, we only return the function name of this function (without parentheses'()').
Use the function name as an argument:
Def hello (): print ("hello") def function1 (func): # receives a parameter print ('before call hello!') Func () print ('after call hello!') # function2 () # use this function function1 (hello) # inside the function to pass hello as an argument
Print as follows:
Before call hello!
Hello
After call hello!
As can be seen from the print, the receive parameter func that we defined in the function function1 is not defined in any special way, but is defined in the same way as the normal parameter. After that, the use of calling function1 externally, passing the function name hello as an argument. Then we run function1 and successfully call the hello function in function1.
Further implementation of the decorator
Now, let's take a fresh look at what a decorator is. When we use the function name as an argument above, we have implemented a function similar to the decorator. If our hello () function is our function and function1 is our decorator, then we have successfully added other print content by using it as an argument without changing the hello () function.
Although we have implemented a decorator-like function above, we can see that when using this, we need to pass a function to function1 every time, which is very troublesome to use. Let's modify this function:
Def decorator (func): # decorator function, which receives a function argument def wrapper (): # defines an inner function wrapper print ('before call hello!') Func () print ('after call hello!') Return wrapper # take the inner function as the unreturned value def hello (): print ("hello") hello = decorator (hello) # redefine a function hello1hello () # execute hello
Print as follows:
Before call hello!
Hello
After call hello!
As you can see from the print above, our newly changed function can achieve the same function as the function above. However, it is easier to use it here than before, because we can directly use the old function name to use the new function (here we are equivalent to assigning a new function wrapper to the function name hello). When we want to use the old function, we just need to comment out the line hello=function (hello).
Use the Python decorator statement:
Simple decorator
We have implemented the function of a decorator above, so let's test it with the decorator that comes with Python:
Def decorator (func): # decorator function, which receives a function argument def wrapper (): # defines an inner function wrapper print ('before call hello!') Func () print ('after call hello!') Return wrapper # takes the inner function as the return value @ decorator #'@'is the decorator syntax def hello (): print ('hello') hello ()
Print as follows:
Before call hello!
Hello
After call hello!
As you can see, we use the system's built-in decorator syntax to achieve the same function as the function above.
Here we can see that the only difference between the two is that they use the symbol @ decorator instead of the assignment statement hello=decorator (hello).
At this point, we basically understand the principle and practical use of python's so-called decorator, but here we still have a question, that is, will this method change the properties of our functions?
Let's test it:
Print (hello.__name__)
Print as follows:
Wrapper
Obviously, the function name in the property of our original function has been changed, in fact, through the above own implementation, we can find that we use the decorator syntax is to create a new function name, and then use it to receive the decorator function return function name, so that the function must still inherit the decorator return function name.
To solve this problem, we can use the following methods:
Import functools def function (func): # receives a parameter @ functools.wraps (func) def wrapper (): # defines an inner function wrapper print ('before call hello!') Func () print ('after call hello!') Return wrapper # takes the inner function as the return value @ function #'@'is the decorator syntax def hello (): print ('hello') hello () print (hello.__name__)
Print as follows:
Before call hello!
Hello
After call hello!
Hello
By using the system module, we have solved this problem.
Decorator with parameters:
Above we show the basic usage of the decorator, but we can find a problem, that is, this decorator can only be used to print a class of basic operations, and sometimes we need to pass parameters in the decorator function. and need to use the same decorator function in multiple functions, it is not easy to use the above method alone.
Let's show a method of passing parameters to the decorator:
Import functoolsdef logging (level): # decorator receives parameter function def decorator (func): # decorator function Used to receive a function @ functools.wraps (func) def wrapper (* args) * * kwargs): # define an inner function wrapper if level = = 'warn': print (' warn: before call% s!'% func.__name__) func () print ('warn: after call% s!'% func.__name__) if level = = 'error': print ('error: before call% s!'% func.__name__) func () print ('error: after call% s!'% func.__name__) return wrapper # takes the inner function as the return value return decorator@logging (level='warn') #'@'is the decorator syntax def hello (): print ('hello') that comes with the system @ logging (level='error') def function1 (): print ('function1') hello () function1 () print (hello.__name__) print (function1.__name__)
Print as follows:
Warn: before call hello!
Hello
Warn: after call hello!
Error: before call function1!
Function1
Error: after call function1!
Hello
Function1
As you can see, we used a decorator syntax in the two functions and passed different parameters to the decorator to compare the symbols we might actually use.
It may feel a little complicated for the first time here, and we also use multi-layer function nesting here, each passing different parameters. Here, let me split this function in detail:
First of all, we know:
@ loggingdef hello (): print ('hello') # is equivalent to logging (hello)
Therefore:
@ logging (level='warn') def hello (): print ('hello') # is equivalent to logging (hello) (level='warn')
Let's continue to unravel the sentence logging (hello) (level='warn'):
Logging (hello) (level='warn')
Due to
Logging (hello) returns decorator
So
Logging (hello) (level='warn')
Equivalent to
Decorator (level='warn')
And
Decorator returns wrapper
therefore
This is actually our top simple decorator.
At this point, we understand what is going on with our decorator.
Decorator class:
Because we often use classes to encapsulate a function in python, it is more flexible and convenient when we use a function.
Therefore, our python also gives us a way to implement the decorator class:
Class Logging (object): def _ init__ (self, func): self._func = func def _ call__ (self): print ('class: before call% s!'% self._func.__name__) self._func () print ('class: after call% s!'% self._func.__name__) @ Loggingdef hello (): print ('Hello') hello ()
Print as follows:
Class: before call hello!
Hello
Class: after call hello!
As you can see, the use of our class decorator is similar to that of a function, except that when defining a decorator function, we change the implementation of the function into the implementation of the class method.
In addition to this basic use, we can also pass parameters to the class decorator:
Class Logging (object): def _ init__ (self, level='INFO'): self._level = level def _ call__ (self, func): def wrapper (* args * * kwargs): if self._level = 'WARN': print (' class: warn before call% s!'% func.__name__) func () print ('class: warn after call% s!'% func.__name__) return wrapper@Logging (level='WARN') def hello (): print ('Hello') hello ()
Print as follows:
Class: warn before call hello!
Hello
Class: warn after call hello!
The method of passing parameters here is a little different from defining a function directly in _ _ call__ in the class above. You need to keep two points in mind here:
_ _ init__: no longer receives decorated functions, but receives incoming parameters
_ _ call__: receives the decorated function and implements the decorative logic
This class method will not be parsed in depth here.
At this point, the study on "what are the basic functions of the decorator in Python" 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.