[chapter 08 - closures and decorators 01] Introduction to closures

1, Closure

1.1 introduction to closures

We have learned about the function before. We know that when the function is called, the variables defined in the function are destroyed, but sometimes we need to save the variable in the function and complete some column operations based on the variable every time. For example, what should we do every time we sum with other numbers based on the variable?

1.2 definition of closure

On the premise of function nesting, the internal function uses the variables of the external function, and the external function returns the internal function. We call this internal function using the external function variables as closure.

1.3 composition conditions of closure

Through the definition of closure, we can know the formation conditions of closure:
(1) On the premise of function nesting (function is defined inside the function)
(2) The internal function uses the variables of the external function (including the parameters of the external function)
(3) An external function returned an internal function

Sample code for simple closures

# Define an external function
def func_out(num1):
    # Define an internal function
    def func_inner(num2):
        # The internal function uses the variable (num1) of the external function
        result = num1 + num2
        print("The result is:", result)
    # The external function returns the internal function, and the internal function returned here is the closure
    return func_inner

# Create closure instance    
f = func_out(1)
# Execute closure
f(2)
f(3)

Operation results:

The result is: 3
 The result is: 4

1.4 function of closure

Closures can save variables in external functions and will not be destroyed when external functions are called.
Note:
Because the closure refers to the variables of the external function, the variables of the external function are not released in time and consume memory.

1.5 summary

When the returned internal function uses the variables of the external function, a closure is formed
Closures can save variables of external functions
Standard format for implementing closures:

 # External function
 def test1(a):
     b = 10
     # Internal function
     def test2():
         # Internal functions use variables or parameters of external functions
         print(a, b)
     # Return the inner function, which is the closure instance
     return test2

2, Use of closures

2.1 cases

Requirements: use closures to realize the dialogue information of different people according to the configuration information, such as dialogue:

Zhang San: have you arrived in Beijing? Li Si: it's already here. Don't worry.

2.2 description of implementation steps

  1. Define external functions to receive different configuration information parameters. The parameters are person names
  2. Define the parameters for the internal function to receive dialog information
  3. The configuration information and dialog information are spliced and output in the internal function

2.3 implementation of function code

# External function
def config_name(name):
    # Internal function
    def say_info(info):
        print(name + ": " + info)

    return say_info

tom = config_name("Tom")

tom("Hello!")
tom("Hello, are you there?")

jerry = config_name("jerry")

jerry("be not in, Don't play!")

Operation results:

Tom: Hello!
Tom: Hello, are you there?
jerry: be not in, Don't play!

2.4 closure case description:

  • Closures can also improve code reusability without manually defining additional functional functions.

2.5 summary

  • Closures can not only save the variables of external functions, but also improve the reusable lines of code.

3, Modify external variables used within closures

3.1 modify external variables used in closures

Error example of modifying external variables used in closures:

# Define an external function
def func_out(num1):

    # Define an internal function
    def func_inner(num2):
        # The intention here is to modify the value of external num1. In fact, a local variable num1 is defined in the internal function
        num1 = 10
        # The internal function uses the variable (num1) of the external function
        result = num1 + num2
        print("The result is:", result)

    print(num1)
    func_inner(1)
    print(num1)

    # The external function returns the internal function, and the internal function returned here is the closure
    return func_inner

# Create closure instance
f = func_out(1)
# Execute closure
f(2)

Error example of modifying external variables used in closures:

# Define an external function
def func_out(num1):

    # Define an internal function
    def func_inner(num2):
        # The intention here is to modify the value of external num1. In fact, a local variable num1 is defined in the internal function
        nonlocal num1  # Tell the interpreter that the external variable a is used here
        # Modify external variable num1
        num1 = 10
        # The internal function uses the variable (num1) of the external function
        result = num1 + num2
        print("The result is:", result)

    print(num1)
    func_inner(1)
    print(num1)

    # The external function returns the internal function, and the internal function returned here is the closure
    return func_inner

# Create closure instance
f = func_out(1)
# Execute closure
f(2)

3.2 summary

  • Modify the external function variables used in the closure and use the nonlocal keyword.

Keywords: Python data structure

Added by abhic on Sun, 05 Dec 2021 17:04:18 +0200