A detailed introduction and example of closures in Python, and a detailed introduction to python
I. Closure
From wiki:
Closure is short for Lexical Closure, a function that references free variables. This referenced free variable will exist with this function, even if it has left the environment where it was created. Therefore, there is another saying that a closure is an entity composed of a function and its reference environment.
In some languages, when defining another function in a function, if an internal function references a variable of an external function, a closure may be generated. During runtime, once an external function is executed, a closure is formed. The closure contains the code of the internal function and the reference of the variables in the required external function.
Closure purpose:
The closure can be used to define the control structure only when it is called.
Multiple Functions can use the same environment, so that they can communicate with each other by changing that environment.
From baidu Encyclopedia:
The value of a closure is that it can be used as a function object or an anonymous function. For a type system, this means not only data but code. Most languages that support closures use functions as the first-level objects. That is to say, these functions can be stored in variables and passed as parameters to other functions, the most important thing is that functions can be dynamically created and returned.
Ii. Closure in python
Instance:
Copy codeThe Code is 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 ())
Iii. lamada
Instance:
Copy codeThe Code is as follows:
Def f (x ):
Return x ** 2
Print f (4)
G = lambda x: x ** 2
Print g (4)
Is lambda really useless in Python? Actually not. At least I can think of the following points:
1. When using Python to write some execution scripts, using lambda can save the process of defining functions and simplify the code.
2. For some abstract functions that will not be reused elsewhere, it is also difficult to give them a name. You do not need to consider naming when using lambda.
3. Use lambda to make the code easier to understand in some cases.