Python-depth understanding of closures

1. What is closure:

  Closure is able to read in a scope from its other functions scope of local variables of the function , common in javascript, while in Python also exists the phenomenon of closure, and get better support.

 

2. The closure forming conditions:

  The overall function of the body type of higher-order function (explained: a function as an argument to another function, or a function of another function return value (if the return value of the function itself, for the recursion), which satisfies compared with a higher-order function)

  Popular terms : it is the definition of a function at a certain internal functions

 

3. To achieve

  Let's take a simple closure (not modify variables outer_var, read only) Example:

def outer () 
    outer_var = 1
     def inner () 
        inner_var = outer_var +100
         print ( ' inner: \ t% s ' %   inner_var)
     return inner

  Execution results are as follows:  

  

  Explain: func = Outer () after, in fact, equivalent  func = Inner , final func ()  corresponds to the execution Inner () , except that which func the function reference point

  

 

Guess you like

Origin www.cnblogs.com/kisun168/p/11202074.html