Talk about your understanding of the closures?

Closures difficult to understand this concept is good, a lot of their friends are sleepwalk, sleepwalk Lin old Cold want to write this article can be of some help to sleepwalk partners ~

 

Please understand me look, if you define a function within another function, external function outside we call him, call him within our internal function.

Closure: 

  Definition of a function within an external function, the function in the use of temporary variables outside the function and the return value is outside the reference function. This constitutes a closure.

In general, in our perception of them, if a function is over, everything will be relieved of internal functions, returned to memory, local variables will disappear. But the closure is a special case, if the external function found at the end of their temporary variables inside the function will be used in the future, put the temporary variable is bound to an internal function, and then ended his own again.

  Very obscure difficult to understand ah! ! Let's look at a piece of code ^. ^

Copy the code

 1 Example # closure function
 2 # outer external functions are temporary variables a and b are outside the function
 3 def outer( a ):
 4     b = 10
 5 # inner function within
 6     def inner():
 # 7 inner function uses temporary variables outside the function
 8         print(a+b)
 # 9 function return value is a reference to the external function
10     return inner
11 
12 if __name__ == '__main__':
13 # Here we call the outer function parameters passed 5
# 14 outer case is a function of two variables temporary 5 b is 10, and the function is created, then the function returns a reference to the stored demo
# 15 was found outside a function of the end of the function will use its own internal temporary variables, these two variables will not be temporary release, we will be bound to the internal function
16     demo = outer(5)
# 17 we call the internal function, take a look at the internal functions are not able to use external functions of temporary variables
18 # demo stored outside the function return values, i.e. referenced inner function, where the function corresponding to the implementation of inner
19     demo() # 15
20 
21     demo2 = outer(7)
22     demo2()#17

Copy the code

 

From the above example is I wrote a simple typical closure. I guess if it is beginner's junior partner, probably many nouns do not understand what that means, it does not matter, I put these terms according to their own understanding to explain ~

The external function returns a reference to the function:

  What references are? Everything is an object in python, including 1 integer data, function, in fact, is the object.

  When we conduct a = 1, when in fact there is a place to store the value 1, then the variable name with a reference to a deposit where the memory location in memory of them. C language reference just like pointers, we can understand the reference to an address. a variable is just a name, a deposit which is the address where this number 1, which is a reference value saved 1.

  The same token, when we define a function def demo () in python: when the memory of them will open up some space, able to save the function code, local variables, and so on inside. This demo is just a variable name, which kept it a reference to the location of the function only. We can also x = demo, y = demo, this operation is equivalent to, the demo was assigned to keep things x and y, x and y are such a reference point to where the demo function, after which we can use x () or y () call to create our own demo (), called in fact simply a function, x, y and demo saved three variable names refer to the same function.

  I do not know if you have not understood very obscure, I hope I understand that I want to express.

  With the above explanation, we can continue to say, back into the reference function is how the story. For closures, the outer outer function last return inner, outer function we call demo = outer () when, returned inner outer, inner is a reference function, this reference is stored in the demo. So next time we'll be demo (), the equivalent of running the inner function.

  We found a function, if followed by a pair of parentheses after the function name, the equivalent now I'm going to call this function, if not followed by parentheses, the equivalent of the name is just a function, which kept the location where the function reference.

2 temporary variables outside a function to bind to the inner function:

  According to our normal cognitive, ending a function of time, to make their temporary variables are released back to the memory, after the variables do not exist. Under normal circumstances, is indeed the case. However, the closure is a special case. External functions found their temporary variables will be used in future internal function, at the end of himself, back into the function at the same time, temporary variables to the outside will function within the function to bind together. So outside of the function is over, when calling within the function will still be able to use temporary variables outside the function.

  In the example I have written, I have two calls to external functions outer, respectively the incoming values ​​are 5 and 7. Internal function is defined only once, we found that when you call, the internal function is to recognize the temporary variables outside a function is not the same. python, everything is an object, though we function is defined only once, but time is running outside the function is actually executed in accordance with the code inside and outside the function in creating a function, every time we call the outer function, it creates within a function, although the code is the same, but it creates different objects, and to bind each incoming value to a temporary variable within a function, then within the function returns a reference. While inside the function code is the same, but in fact, every time we call external function returns a different instance of an object reference, their function is the same, but they are actually not the same function object.

 

The outer closure function modification function local variables:

  In function closures, we are free to use outside the function to bind to the temporary variables, but if we want to change the value of the temporary variable outside a function of time found a problem! Editor's Note pinching? ? ! ! (Cried)

  Among the basic syntax of python, a function can be read without global data, but to modify global data when there are two methods: 1 global global variable declarations global variable is a variable type 2 data can be modified when

  Closures function within a similar situation. When we want to modify the function in the inner closure variables (bind to the external function local variable function) is:

    1 python3, you can use nonlocal keyword to declare a variable, indicating that the variable is not a variable local variable space, we need to look up a layer of variable space variable.

    2 python2, no nonlocal keyword, we can change the variable type closure variable data modifications, such as a list.

The Code! ! !

Copy the code

 # 1 modified example of closure variables
 2 # outer external functions are temporary variables a and b are outside the function
 3 def outer( a ):
 4 b = 10 # a and b are variable closure
 5 c = [a] # where variables corresponding to the modified method of closure 2
 6 # inner function within
 7     def inner():
 # 8 want to change the function variable closure
 9 # 1 nonlocal keyword method statement
10         nonlocal  b
11         b+=1
Method II # 12, the variable is modified to a variable closure such as a list of data types
13         c[0] += 1
14         print(c[0])
15         print(b)
Return Value # 16 is a reference to a function outside the function
17     return inner
18 
19 if __name__ == '__main__':
20 
21     demo = outer(5)
22     demo() # 6  11

Copy the code

From the above code, we can see it, including function, respectively, for the closure variable is modified, print out the results are indeed the result after revision. The above two methods is the method of modifying the function of closure variable.

 

Another point to note: Use the closure process, once the external function is called once returned to the reference within the function, although each call within a function, a function that is turned on after the demise of execution, but in fact only one copy of the closure variable each time you open within the same function in the use of a closure variable

The Code!

Copy the code

 1 #coding:utf8
 2 def 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(1)) //11
12 print(a(3)) //14

Copy the code

Two were printed out 11 and 14 shows that each inner call when the closure variable x used in fact the same.

 

 

 

 

 

Closures dim? ? ! !

  Many partners are confused, closures dim ah? ? Also so difficult to understand!

   3.1 decorator! ! ! Decorator is doing what? ? One application is that we work to write a login function, we want this function to perform statistical how long it took, we can decorate the login module, decorators help us complete the login function before and after the execution to take time with the decorator.

   3.2 Object-oriented! ! ! Experienced the above analysis, we found that temporary variables of the outer function within the given function. We recall the case of the class object, the object has a lot of similar attributes and methods, so we create a class, created out of a class of objects have the same attributes method. Closures also achieve one object-oriented approach. In this python Although we do not use them, in other programming languages ​​into such avaScript, the closures are often used to achieve the object-oriented programming

   Example 3.3 for single mode! ! In fact, this is the application of the decorator. Singleton, after all, relatively tall, need to have some project experience to understand the Singleton pattern in the end is doing with, we would not explored.

 

 

Talk about my problems encountered when learning of the closure, after solving their own understanding. I want to help novice friends. Great God also welcome other partners to criticism and communication -

 

Published 522 original articles · won praise 52 · views 70000 +

Guess you like

Origin blog.csdn.net/sinolover/article/details/104254502