Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

Hello everyone, I am a bowl week, a front end that does not want to be drunk (inrolled). If I am lucky enough to write an article that you like, I am very lucky

closure

The concept of closures in a function is simply that a function definition refers to variables defined outside the function, and that the function can be executed outside the context in which it is defined. Such a function is called a closure. Closures can actually be thought of as a more general functional concept. Because it’s no longer a function in the traditional sense.

The concept of closures exists not only in Python, but in almost any programming language.

Conditions for closures:

  1. An inner function is defined in an outer function
  2. External functions return values
  3. The return value is: inner function
  4. The inner function also references the variables of the outer function

The format is as follows:

Def external function ():... Def inner function ():... Return internal functionCopy the code

The sample code

def func(): a = 100 def inner_func(): b = 200 print(a, b) return inner_func x = func() print(x) # <function func.<locals>.inner_func at 0x0000021704CD9620> x() # 100 200 # You can call inner_func directly, and there is no output if the return does not return an inner functionCopy the code

You can also use closures to achieve the effect of a counter

def generate_count(): container = [0] def add_one(): Container [0] += 1 print(f" this is the first {container[0]} call ") return add_one count = generate_count() count() # This is the second call to count() # and this is the third callCopy the code

The disadvantages of closures are as follows:

  1. The scope is not as straightforward
  2. There is a memory footprint because variables are not garbage collected.

Closures are used as follows:

  1. Peer scopes can be used
  2. Reads internal variables of other elements
  3. Extended scope