anonymous funct...LOGIN

anonymous function

Have you ever thought about defining a very short callback function, but don’t want to use def to write such a long function? Is there a shortcut? The answer is yes.

Python uses lambda to create anonymous functions, that is, you no longer use the standard form of def statement to define a function.

Anonymous functions mainly have the following characteristics:

lambda is just an expression, and the function body is much simpler than def.

The body of lambda is an expression, not a code block. Only limited logic can be encapsulated in lambda expressions.

The lambda function has its own namespace and cannot access parameters outside its own parameter list or in the global namespace.

Basic syntax

lambda [arg1 [,arg2,.....argn]]:expression

Example:

# -*- coding: UTF-8 -*-
sum = lambda num1 , num2 : num1 + num2;
print( sum( 1 , 2 ) )

Output result:

3

Note:Although lambda expression Allows you to define simple functions, but its use is limited. You can only specify a single expression, and its value is the final return value. That is to say, it cannot contain other language features, including multiple statements, conditional expressions, iteration, exception handling, etc.

In anonymous functions, there is a special issue that requires attention. For example, change the above example:

# -*- coding: UTF-8 -*-
num2 = 100
sum1 = lambda num1 : num1 + num2 ;
num2 = 10000
sum2 = lambda num1 : num1 + num2 ;
print( sum1( 1 ) )
print( sum2( 1 ) )

What do you think the output will be? The first output is 101, the second is 10001, the result is not, the output result is like this:

10001
10001

This is mainly because num2 in the lambda expression is a free variable, and the value is bound at runtime , instead of binding when defining, which is different from the default value parameter definition of the function. Therefore, it is recommended to use the first solution when encountering this situation.

Next Section
submitReset Code
ChapterCourseware