Python anonymous function

Use the lambda keyword to create small anonymous functions. This function gets its name from omitting the standard step of declaring a function with def.
The syntax of a lambda function consists of only one statement, as follows:

lambda parameter1, parameter2,...: expression

>>> sum = lambda x,y:x+y
>>> print(sum(10,20))
30

#Application 1: In this case, only specific functions can be completed 
>>> def test(a,b,func):
...     result = func(a,b)
...     print(result)
...
>>> test(10,20,lambda x,y:x+y)
30

#Application 2: Advanced 
# python is a dynamic language, you can input anonymous functions with specific functions according to the needs of users 
>>> def test(a,b,func):
...     result = func(a,b)
...     print(result)
...
>>> func_new = input( " Please enter an anonymous function: " )
Please enter an anonymous function: lambda x,y:x- y
 >>> func_new = eval(func_new)
 >>> test(10,20 ,func_new)
 -10

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325233272&siteId=291194637