Talk about your understanding: The nature of closures, closures in python

Source: Internet
Author: User
Tags closure

Closure of the concept is very difficult to understand, friends around a lot of confused, confused Lin Old Cold hope to write this article to the confused partners have some help ~

Please understand that if another function is defined inside a function, we call him outer function, inside we call him inner function.

Closures:

An inner function is defined in an outer function, and a temporary variable of the outer function is used in the inner function, and the return value of the outer function is a reference to the inner function. This makes up a closure.

In general, in our cognition, if a function ends, everything inside the function is released, back to memory, and local variables disappear. But closure is a special case, if the outer function at the end of the discovery of its own temporary variables in the future will be used in the internal function, the temporary variable is bound to the internal function, and then end themselves.

Very obscure difficult to understand Ah!! Let's take a look at the code ^.^

1#An example of a closed packet function2#Outer is a temporary variable that external functions A and B are external functions3DefOuter (a):4 B = 105#Inner is an intrinsic function6DefInner ():7#A temporary variable of the outer function is used in the inner function.8Print (A +b9#The return value of the outer function is a reference to the inner function10ReturnInner1112If__name__ = =‘__main__‘:13#Here we call the outer function passed in parameter 514#At this point the outer function two temporary variable A is 5 B is 10, and created an inner function, and then the internal function of the reference back to the demo  when the outer function ends, the internal function will use its own temporary variable, and the temporary variables will not be freed and bound to the intrinsic function. demo = outer (5) # # We call internal functions , take a look at whether an intrinsic function can use a temporary variable of an external function. The   demo Saves the return value of the outer function, which is the reference to the inner function, which is equivalent to executing the inner function, demo () # 15  Demo2 = outer (7)Demo2 ()#         

From the above example is one of the simplest and most typical closures I have written. I guess if it is a beginner's little friend, maybe a lot of nouns do not understand what it means, it's OK, I put these nouns according to their understanding to explain ~

The 1 outer function returns a reference to the inner function:

What is a reference? In Python everything is an object, including integer data 1, a function, actually an object.

When we do a=1, we actually have a value of 1 in memory, and then we use a variable name to save 1 of the memory location of the reference. References are like pointers in C, and you can interpret references as addresses. A is just a variable name, a contains 1 of the value of the address, that is, a has stored a value of 1 of the reference.

In the same way, when we define a function Def demo () in Python, the memory will open up some space, the code of the function, the local variables inside, and so on. This demo is just a variable name, which contains a reference to the location of the function. We can also do x = demo, y = demo, which is equivalent to assigning the contents of the demo to X and Y, so that both X and Y point to the reference where the demo function is located, after which we can use X () or Y () to invoke our own demo (), the actual root of the call This is a function, x, Y, and demo three variable names save a reference to the same function.

I do not know whether you understand, very obscure, I hope that I understand what I want to express.

With the above explanation, we can continue to say that the return inside the function reference is going on. For closures, the last return inner in the outer function outer, when we called the outer function demo = outer (), outer returned the Inner,inner is a reference to the function, which is stored in the demo. So the next time we do the demo (), it's equivalent to running the inner function.

At the same time, we find that a function, if the function name immediately after a pair of parentheses, the equivalent of now I will call this function, if not with the parentheses, the equivalent of just a function name, where the function is stored in the reference.

2 The outer function binds the temporary variable to the inner function:

According to our normal perception, when a function ends, it releases its temporary variables back into memory, and then the variables do not exist. In general, this is indeed the case. But closures are a special case. External functions find that their temporary variables will be used in future internal functions, and at the end of the time, return the inner function at the same time, the outer function of the temporary variables are sent to the inner function bound together. So the outer function is over, and the external function's temporary variable can still be used when the inner function is called.

In the instance I wrote, I called the external function outer two times, and the values passed in were 5 and 7, respectively. The inner function is defined only once, and we find that when called, the intrinsics are not the same as temporary variables that recognize the outer function. In Python everything is an object, although the function is defined only once, but when the outer function is run, it is actually executed according to the code inside, the outer function creates a function, each time we call the outer function, it creates an inner function, although the code, but creates a different object, And the value of each incoming temporary variable is bound to the inner function, and then the inner function reference is returned. Although the inner function code is the same, in fact, every time we call an outer function, we return a reference to a different instance object, their function is the same, but they are not actually the same function object.

The inner function in the closure modifies the outer function local variables:

In the inside of the closure function, we are free to use the temporary variable bound by the outer function, but if we want to modify the value of the outer function temp variable, we find the problem! What's the pinch??!! (Crying loudly)

In the basic Python syntax, a function can read the global data at will, but there are two ways to modify global data: 1 global declares that Globals 2 global variables are mutable type data can be modified

Inside the closure function is a similar situation. When you want to modify the closure variable in the inner function (the outer function is bound to the local variable of the inner function):

1 in Python3, you can declare a variable with the nonlocal keyword, which means that the variable is not a variable in the local variable space, and it needs to be looked up in a variable space.

2 in Python2, there is no nonlocal this keyword, we can change the closure variable to variable type data for modification, such as list.

On the code!!!

1#Modifying an instance of a closure variable2#Outer is a temporary variable that external functions A and B are external functions3DefOuter (a):4 B = 10#Both A and B are closure variables5 C = [A]#Here corresponds to the method of modifying the closure variable 26#Inner is an intrinsic function7DefInner ():8#The inner function wants to modify the closure variable9#Method 1 nonlocal Keyword declaration10Nonlocal bB+=112#Method Two, change the closure variable to a variable data type such as ListC[0] + = 114Print (C[0]) 15 print (b) 16 # The return value of the outer function is a reference to the inner function 17 return Inner18 19 if __name__ = =  ' __main__ ' :20 21 demo = Outer (5) 22 demo () # 6             

From the above code we can see that in the inner function, the closure variable is modified, the printed result is indeed the result of the modification. The above two methods are the method that the inner function modifies the closure variable.

It is also important to note that in the process of using closures, once the outer function is called to return a reference to the inner function, although each call to the inner function is to open a function after the execution of the extinction, but the closure variable is actually only one copy, each open inside the function is using the same closure variable

On the code!

1#Coding:utf82def outer (x):  3 def inner (y):  4  nonlocal x 5 x+=y 6 return x  7 return Inner 8  9 10 a = outer (10) 11 print (A (112 print (A (3))//14       

Two times print out 11 and 14 respectively, so that each time the call inner, the use of the closure variable x is actually the same.

What's the use of closures??!!

Many partners are confused, what is the use of closures? It's so hard to understand!

3.1 Decorator!!! What does an adorner do? One of the applications is that we have written a login function in our work, we want to count how long it took the function to execute, we can decorate the login module with the decorator, and the decorator helps us to finish the time before and after the login function is executed.

3.2 Object-oriented!!! Through the above analysis, we find that the temporary variables of the outer function are given to the inner function. Recall the case of class objects, objects have a lot of similar properties and methods, so we create classes, objects created with the class have the same property methods. Closures are also one of the implementations of object-oriented methods. In Python, although we do not use this, in other programming languages such as avascript, often using closures to implement object-oriented programming

3.3 Implement simple interest mode!! In fact, this is also the application of adorners. Simple interest mode is relatively tall after all, it is necessary to have a certain project experience to understand the simple interest model is what the use of, we do not discuss.

Talk about my study in the closure of the problems encountered when the solution to their own understanding. Hope to be helpful to beginners ' good friends. Other great God partners are also welcome to criticize, communicate and communicate ~

Talk about your understanding: The nature of closures, closures in python

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.