Talk about their own understanding: python in closures, the closure of the essence.

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

 1 #闭包函数的实例
 2 # outer是外部函数 a和b都是外函数的临时变量
 3 def outer( a ):
 4     b = 10
 5     # inner是内函数
 6     def inner():
 7         #在内函数中 用到了外函数的临时变量
 8         print(a+b)
 9     # 外函数的返回值是内函数的引用
10     return inner
11 
12 if __name__ == '__main__':
13     # 在这里我们调用外函数传入参数5
14     #此时外函数两个临时变量 a是5 b是10 ,并创建了内函数,然后把内函数的引用返回存给了demo
15     # 外函数结束的时候发现内部函数将会用到自己的临时变量,这两个临时变量就不会释放,会绑定给这个内部函数
16     demo = outer(5)
17     # 我们调用内部函数,看一看内部函数是不是能使用外部函数的临时变量
18     # demo存了外函数的返回值,也就是inner函数的引用,这里相当于执行inner函数
19     demo() # 15
20 
21     demo2 = outer(7)
22     demo2()#17

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.

3. 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? ? ! !

  Among the basic syntax of python, a function can be read without global data, but when you want to modify global data in two ways:

1. Global declare global variables

2 global variable is a variable type of 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. In 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. In python2, no nonlocal keyword, we can change the variable type closure variable data modifications, such as a list.

The Code! ! !

 1 #修改闭包变量的实例
 2 # outer是外部函数 a和b都是外函数的临时变量
 3 def outer( a ):
 4     b = 10  # a和b都是闭包变量
 5     c = [a] #这里对应修改闭包变量的方法2
 6     # inner是内函数
 7     def inner():
 8         #内函数中想修改闭包变量
 9         # 方法1 nonlocal关键字声明
10         nonlocal  b
11         b+=1
12         # 方法二,把闭包变量修改成可变数据类型 比如列表
13         c[0] += 1
14         print(c[0])
15         print(b)
16     # 外函数的返回值是内函数的引用
17     return inner
18 
19 if __name__ == '__main__':
20 
21     demo = outer(5)
22     demo() # 6  11

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 the closure variable is actually only one copy , every time you open within the same function in the use of a closure variable

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

 

Two were printed out 11 and 14 shows that each inner calls when using the closure variable x is actually the same .

Closures dim? ? ! !

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

  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.

  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. The single-mode! ! ! In fact, this application is the decorator. Singleton, after all, relatively tall, need to have some project experience to understand simple interest pattern in the end is doing with, we would not explored.

Published 131 original articles · won praise 7 · views 30000 +

Guess you like

Origin blog.csdn.net/weixin_43064185/article/details/103647068
Recommended