An article to make you understand the Python decorator

Source: Internet
Author: User
Tags closure variable scope python decorator

Take a look at the scope problem in Python before you look at the closure problem

Variable scope

There is no doubt about the error in the code above, after all, B is not defined and assigned, when we change the code as follows:

Let's look at an example:

First of all, this error is very obvious: it says that the local variable B is referenced before the assignment

Maybe a lot of people think that will print 10 and then print 6, in fact, this is the scope of the variables involved in the problem
When Python compiles the definition of a function, it determines that B is a local variable, after all, B = 9 in the function is assigned to B, so Python gets b from the local environment, and when we invoke the execution of the method, the definition acquires and prints the value of the variable A. But when I try to get the value of B, I find that B has no bound value, so you can set B to global if you want to run the above code, or put a B assignment before the call.

Scope of Function Object

All objects in Python, like other objects, function objects have scopes that they use, that is, function objects.
In Python we define functions through Def, where the scope of the function object is the same as the level at which the def resides.
This is understood by the following code:

def func1 ():     def Func2 (x):         return     xprint(FUNC2 (5)) func1 ()print(FUNC2 (5))

In this example we can call fun2 in the Def func1 function, but we can't call to Func2 outside, so the result is as follows:

Closed Package

There are two main kinds of statements about closures:

    • Closures are functions that meet certain conditions, defined as: A closure is a function that refers to a free variable in its lexical context
    • Closures are entities that are combined by functions with their associated reference environment. Defined as: When implementing binding, you need to create something that shows the reference environment and bundle it with the associated subroutine so that the whole bundle is called a closure.

Personally, the second statement is more accurate, the closure is only in the form of performance functions, actually not functions.
Our definition of the function is: some executable code, which is determined after the function definition, does not change at execution time, so a function has only one instance.

Closures can have multiple instances at run time, and different reference environments and the same environment combination can produce different instances.

Here is a word: the reference environment, in fact, refers to the environment is at some point in the execution of the run, all the variables in the active state of the collection, where the variable is the name of the variable and the object it represents the connection between.

The features of the closure language can be used:

    • A function can be a return value or a parameter to another function, and can also be used as a value for a variable.
    • Functions can be nested using

And the one word that the closure is a function is:
A closure is a function that extends scope, which contains a reference in the body of a function definition. However, non-global variables are not defined in the definition body.

The above statement personally felt that it was also a way of understanding

Believe that these concepts are still not good understanding, or through the following examples to better understand:

A method of calculating the mean is implemented first:

From the results, we can see that the historical values are saved each time.
Another way to achieve this:

Achieve the first of the same effect, analysis of this method:
Usually we think that when we call AVG (10) The Make_averager function has returned, and its local scope is gone, but in fact the series is a free variable, a variable that is not bound in the local scope
We can see the following results through print (DIR (avg)):

In fact, the name of the uniform variable and the free variable is preserved here, we can view it by the following methods:

The binding of the eries is in the __closure__ property of the returned AVG function, which is probably what some people would consider a function of closure. Closures retain the binding of the free variables that exist when the function is defined, so that when the function is called, the scope of the definition cannot be used, but those bindings can still be used

About nonlocal

When you start to understand closures, it is easy to use this programming method to make the following error examples:

def Make_averager ():     = 0    = 0    def  Averager (new_value):        + =        1 + = new_ Value        return total/ count    return Averager

Let's take a look at the error tip:

The difference between this example and the one we used above is that the count and total here are numbers and are immutable types, whereas the previous example in series is a list of mutable types
So here we go back to the beginning of the scope of the problem, when we use in the Averager
Count + = 1 is actually count = count + 1, so that count is assigned to the Averager function definition body, and count becomes a local variable.

Summary of the problem: when the number, string, tuple and other immutable types, can only read can not be updated, if the use of similar to count + = 1 will implicitly put count into a local variable, so the beginning of the example using the series, we follow the operation is append and list or Mutable object

But Python3 introduced a new keyword nonlocal, which marks the variable as a free variable, so we simply change the example of the above error:

def Make_averager ():     = 0    = 0    def  Averager (new_value):        nonlocal count,total        + = 1               + = new_value Return total/Count return          Averager

The prelude to the decoration here is finished, the following is the adorner, I personally think that the decorator is only a closure of the application, closures in many cases is a very good turn into a skill

Decorative Device

About the adorner was originally wanted to rearrange, looked at their own before the blog, already quite detailed, put the connection directly here
http://www.pythonsite.com/?p=113

An article to make you understand the Python decorator

Related Article

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.