First, closures
From wiki:
Closure (Closure) is the abbreviation of lexical closure (lexical Closure), which is a function that references a free variable. The referenced free variable will exist with this function, even if it has left the environment that created it. So, there is another saying that closures are entities that are combined by functions and reference environments associated with them.
In some languages, when you define another function in a function, a closure can occur if the internal function references a variable of an external function. At run time, once the external function is executed, a closure is formed, and the closure contains the code for the internal function, as well as a reference to the variable in the desired external function.
Closures for use:
Because closures are performed only when invoked, they can be used to define control structures.
Multiple functions can use the same environment, which allows them to communicate with each other by changing the environment.
From Baidu Encyclopedia:
The value of closures is that it can be a function object or an anonymous function, which means not only representing the data but also representing the code for the type system. Most languages that support closures use functions as first-level objects, meaning that they can be stored in variables, passed as arguments to other functions, and, most importantly, can be created and returned dynamically by functions.
Second, the Python closure
Instance:
Copy Code code as follows:
Def make_counter ():
Count = 0
Def counter ():
nonlocal count
Count + 1
return count
Return counter
Def make_counter_test ():
MC = Make_counter ()
Print (MC ())
Print (MC ())
Print (MC ())
Third, Lamada
Instance:
Copy Code code as follows:
def f (x):
Return x**2
Print F (4)
g = Lambda x:x**2
Print g (4)
Is the lambda in Python really useless? In fact not, at least I can think of points, mainly:
1. When using Python to write some execution scripts, using a lambda eliminates the process of defining the function and makes the code more streamlined.
2. For some abstract functions that will not be reused elsewhere, it is sometimes difficult to name a function, and you do not need to consider naming problems with a lambda.
3. Using a lambda makes the code easier to understand at some point.