Closures in Python are described and instantiated in detail

  • 2020-04-02 14:24:36
  • OfStack

A, closures

From wiki:

Closure (Closure) is Lexical closures (Lexical Closure) for short, is a function of cites a free variable. The referenced free variable will exist with the function, even if it has left the context in which it was created. So, there is another way of saying that a closure is an entity composed of a function and its associated reference environment.

In some languages, when another function is defined within a function, closures can occur if the inner function references the variables of the outer function. At runtime, once an external function is executed, a closure is formed that contains the code for the internal function and references to variables in the required external function.

Closure purpose:

Because closures perform operations 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 that environment.

From baidu encyclopedia:

The value of closures is that they can be used as function objects or anonymous functions, which for a type system means not only representing data but also code. Most languages that support closures treat functions as first-level objects, meaning they can be stored in variables, passed as arguments to other functions, and, most importantly, dynamically created and returned by functions.

Closures in python

Example:


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

Example:


def f(x):
    return x**2 print f(4) g = lambda x : x**2
print g(4)

Is lambda really useless in Python? Not really. At least the points I can think of are:

1. When writing execution scripts in Python, using lambda can simplify the code by eliminating the need to define functions.
2. For some abstract functions that can't be reused anywhere else, sometimes it's difficult to give a name to a function, so lambda doesn't have to worry about naming.
3. Using lambda makes the code easier to understand at some point.


Related articles: