Python closures and decorators and python decorations

Source: Internet
Author: User
Tags python decorator

Python closures and decorators and python decorations

What is a decoration device?
Decorator is relatively simple. Let's first introduce it: "the function of the Decorator is to pass the decorated function as a parameter to the function corresponding to the Decorator (the function with the same name ), and return the decorated Function After packaging. "It sounds a little round. It doesn't matter. Let's look at it directly. Here, a is the function corresponding to the decorator @, B is the function decorated by the decorator. The function of the decorator @ a is:

In short: @ a is to pass B to a () and return a new B = a (B)

Chestnuts:

The above uses @ dobi to represent the decorator, which is equivalent to: qinfeng = dobi (qinfeng)
Therefore, the decorator is essentially a syntactic sugar. Its function is to simplify the code to improve code readability. The result of running the code above is:

The parsing process is like this:
1. the python interpreter finds @ dobi and calls the corresponding function (dobi function)
2. Specify a parameter before calling the dobi function. The passed parameter is the modified function under @ dobi, that is, qinfeng ()
3. dobi () function execution, call qinfeng (), and qinfeng () print "dobi"

What is a closure?
First, we have to start with the basic concept. What is a closure? Let's take a look at the explanation on the Wikipedia:
In computer science, Closure is short for Lexical Closure, a function that references free variables. This referenced free variable will exist with this function, even if it has left the environment where it was created. Therefore, there is another saying that a closure is an entity composed of a function and its reference environment. A closure can have multiple instances at runtime. Different reference environments and the same function combination can generate different instances.
....
The two key points mentioned above are free variables and functions. I still have to repeat the meaning of "closure". I hope I can understand it as a closed package. This package is a function, and of course the internal logic of the function, the items in the package are free variables, which can wander around with the package. Of course, there must be a premise that this package was created.
In the Python language, A closure is that you call function A, and function A Returns function B to you. The returned function B is called a closure. The parameter you pass when calling function A is A free variable.
Example:

def func(name):  def inner_func(age):    print 'name:', name, 'age:', age  return inner_funcbb = func('the5fire')bb(26) # >>> name: the5fire age: 26

When func is called, a closure -- inner_func is generated and the closure holds the free variable -- name. Therefore, this means that after the lifecycle of the function func ends, the name variable still exists because it is referenced by the closure and will not be recycled.

In addition, closures are not a special concept in Python. All languages that use functions as first-class citizens have the concept of closures. However, closures can also be used in languages like Java where class is the first-class citizen, but they must be implemented using classes or interfaces.

Nonlocal statement
In a python function, you can directly reference external variables, but cannot rewrite external variables. Therefore, if you directly rewrite the variables of the parent function in the closure, an error will occur:

In python 2, global statements can be used in functions, but global variables are not recommended in any language because they are difficult to control, the nonlocal statement introduced in python 3 solves this problem:

The difference between Nonlocal and global is that the nonlocal statement searches for variables between local variables and global variables, and first searches for external variables closest to hierarchical relationships and closure scopes.

Closure and decorator
The function of the decorator has been briefly demonstrated above. In fact, the decorator is a closure application, but it passes the function:

@ Makeitalic the modifier passes the hello function to the makeitalic function. After the makeitalic function is executed, it returns the packaged hello function, which is actually implemented through the closure. The same is true for @ makebold, But it passes the hello function decorated by @ makeitalic. Therefore, the final execution result <B> is in the <I> outer layer, it is actually an explicit closure:

Function of closure
The biggest feature of a closure is that it can bind the variables of the parent function to the internal function and return the function (that is, the closure) after the variable is bound. In this case, even if the closure environment (parent function) is generated) the closure still exists. This process is similar to the class (parent function) generation instance (closure). The difference is that the parent function is only executed during the call, after the execution is completed, the environment will be released, and the class will be created when the file is executed. Generally, the scope will be released after the program is executed, therefore, for some actions that need to be reused and cannot be defined as a class, the use of closures takes less resources than the use of classes, and is more lightweight and flexible. For example: let's assume that we only want to print the sounds of all kinds of animals, which are implemented by class and closure:

We can see that the output results are exactly the same, but obviously the implementation of classes is relatively cumbersome. Here we just want to output the Animal call and define an Animal class, in addition, after the voice function is executed, its scope has been released, but the corresponding attributes of the Animal class and its instance dog have been stored in the memory:

This occupation is unnecessary after this function is implemented.

In addition, the closure has many other functions, such as encapsulation. In addition, the closure effectively reduces the number of function parameters, which is very valuable for parallel computing, for example, each computer can take charge of a function, and then concatenate it to implement streamlined operations.

Articles you may be interested in:
  • Introduction to functions and function parameters of the python decorator
  • Using the Python decorator without calling the parent class Constructor
  • Example of using the python decorator
  • Python retries decorator example
  • Details about closure instances in Python
  • Closure of Python deep learning
  • Decorator for Python deep learning
  • Summary of closures in Python
  • Decorator usage in Python
  • A detailed tutorial on the decorator, closure, and functools in Python

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.