Learning python (9)-closure function and lamba

1. Closure

Closures, also known as closure functions or closed functions, are actually similar to the nested functions mentioned earlier. The difference is that the outer function in the closure returns not a specific value, but a function. Under normal circumstances, the returned function will be assigned to a variable, which can be executed and called later. Closures have an additional __closure__ attribute than ordinary functions, which records the address of a free variable. When the closure is called, the system will find the corresponding free variable according to the address and complete the overall function call.

Using closures can make the program more concise and readable.

For example: now to write an exponentiation function

def power(number):
    def powermath(base):
        return base**number

    return powermath
 
cube = power(3)
print(cube(5),"of the address is",cube.__closure__)

The output is:

The return value of the external function power() is the function powermath(), not a specific value. The displayed content is an int integer type, which is the initial value of the free variable number in the cube. You can also see that the type of the __closure__ attribute is a tuple, which indicates that the closure can support multiple free variables.

2.lambda

For defining a simple function, Python  also provides another method, that is, using the lambda expression described in this section. Lambda expressions, also known as anonymous functions, are often used to indicate functions that contain only one line of expression inside. If the body of a function has only one line of expression, then the function can be replaced by a lambda expression.

The syntax format of lambda expression is as follows: name = lambda [list]: expression. Among them, to define a lambda expression, you must use the lambda keyword; [list] as an optional parameter is equivalent to defining a function as a specified parameter list; value is the name of the expression.

The lambda expression can be understood in this way, which is a shorthand version of a simple function (the function body is only a single-line expression). Compared with functions, lamba expressions have the following two advantages:

  • For single-line functions, using lambda expressions can save the process of defining functions and make the code more concise;
  • For functions that do not need to be reused multiple times, using lambda expressions can be released immediately after being used up, improving the performance of program execution.

 

Guess you like

Origin blog.csdn.net/qq_35789421/article/details/113567820