Python decorator usage example, pythondecorator

Source: Internet
Author: User
Tags python decorator

Python decorator usage example, pythondecorator

This article describes how to use the Python decorator. Share it with you for your reference. The specific analysis is as follows:

1. closure (closure)

Closures are a feature supported by Python. They allow a function defined in a non-global scope to reference variables in its peripheral space, the referenced variables in these peripheral spaces are called the environment variables of the function. Together with this non-global function, the environment variable forms a closure.
Copy codeThe Code is as follows: def outer (x ):
Y = [1, 2, 3]
Def inner ():
Print x
Print y
Return inner
X = 5 # This x is not referenced
F = outer (2)
F ()
Print f. _ closure _ # function attribute _ closure _ stores the environment variable def entrance (func) of the function ):
= 5 # This x is not referenced. f = outer (2) f () print f. _ closure _ # function attribute _ closure _ stores the environment variable def entrance (func) of the function ):
Both x and y belong to the outer namespace of the function and are referenced in the inner. When the outer function exits, the outer namespace does not exist, however, inner still maintains the connection to its external variables x and y during definition.
Program output:
2
[1, 2, 3]
(,)

The decorator is a callable object. In Python, a function is an object and can also be called. Therefore, the decorator Can be a function, we call it a function modifier.
This callable object uses a function as a parameter, and closes and returns another function (to replace the parameter function ).
For example:

Copy codeThe Code is as follows: def entrance (func ):
Def inner ():
Print "inside function:", func. _ name __
Func ()
Return inner
 
Entrance is a decorator. It is a function that receives a function func as a parameter and returns another function inner.
So why is it called the decorator? In the response function inner (), func () is called and additional operations are performed, which is equivalent to "Decorating" the function func.
So how to use the decorator?

Copy codeThe Code is as follows: def fun1 ():
Pass
Fun1 = entrance (fun1)
Def fun2 ():
Pass
Fun2 = entrance (fun2)
 
The names of fun1 and fun2 have not changed. However, by calling the function decorator entrance (), they have pointed to another function inner () and "decorated" themselves.

@ Operator

The @ symbol provided by Python is essentially the above. It is a syntax technique to assign a new value to a function name. So the above Code is equivalent
Copy codeThe Code is as follows: @ entrance
Def fun1 ():
Pass
@ Entrance
Def fun2 ():
Pass
 
2. decorator usage

From this very simple example of deliberate construction, we can see the significance of the decorator. If a function requires a function, if this function can be used in many functions, or if the function is not implemented by yourself, you can write a decorator to implement these functions.
The above decorator entrance, After decorating a function, the name of this function will be printed when the function is called.
However, there is a problem. In terms of functions, this modifier should be used to describe any function, but if we use it to describe a function with Parameters
Copy codeThe Code is as follows: @ entrance
Def fun3 (x ):
Pass
As long as fun3 is not called, the three lines of code won't let the Python interpreter report an error, because we already know that it is equivalent:
Copy codeThe Code is as follows: def fun3 (x ):
Pass
Fun3 = entrance (fun3)
 
We define a function fun3 with parameters and point fun3 to another function inner (). Of course there will be no error.
 
However, when we use fun3, we will certainly use it according to its definition and input a parameter to it.
>>> Fun3 (1)
Here an error occurs. Let's see how the interpreter reports an error.

Traceback (most recent call last ):
File "decorator. py", line 23, in www.jb51.net <module>
Fun3 (1)
TypeError: inner () takes no arguments (1 given)

Of course, it is easy to know why the error is reported. fun3 does not point to the function defined by it. It now points to "inner ()", the inner does not have a parameter. Of course, an error occurs.
How can this problem be solved?
Modify the definition of inner () so that it can accept any parameter.

Copy codeThe Code is as follows: def entrance (func ):
Def inner (* args, ** kvargs ):
Print "inside function:", func. _ name __
Func (* args, ** kvargs)
Return inner
Now, passing any parameter to the inner will not cause errors, that is, entrance can be used to decorate any function.

3. Write a decorator logger

When a function is called, its name and actual called parameters are recorded in the log.
Copy codeThe Code is as follows: def logger (func ):
Def inner (* args, ** kvargs ):
Print func. _ name __, 'called, arguments: ', args, kvargs
Func (* args, ** kvargs)
Return inner

I hope this article will help you with Python programming.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.