anonymous functions and partial functions
anonymous functions
Python allows you to create anonymous functions using the Lambda keyword, which defines an anonymous function that returns a callable function object with the following syntax:
Lambda arg1, arg2, ...: expression
For example
Lambda a,b=2:a+bprint(Add (3)) # 5Print(add 3, ten) # -
Anonymous functions have a relatively strong functional programming style, such as:
foo = [2, 9, 8, +, +]print filter (lambda x:x% 3 = = 0, foo)prin T map (Lambda x:x% 3 = = 0, foo)
Using lambda expressions, you can avoid defining functions, which makes your code more concise.
Partial function
function parameters in Python can have default values, which can reduce the complexity of function calls, such as:
def Add (A, B, c=100): return a+b+cprint(add (+) ) # the
When a function has too many arguments and needs to be simplified, the partial function (functools.partial) can be used to create a new function that can fix some of the parameters of the original function, making it easier to invoke .
from Import Partial def Add (A, B, c=100): return a+b+= partial (add, c=100)Print (plus (+)) # print(plus ( -20)) # 110
In the above example, partial (add, c=100) uses the keyword parameter c=100, if it is just a simple use of partial (add, 100), then 100 as the positional parameter, will be considered as the fixed value of parameter a. For example:
from Import Partial def Add (A, B, c=100): return a+b+= partial (add, +)print( Plus (+) # 240
Print (plus (40, 50)) # 190
Here, plus (40), the incoming 40 is assigned to B, and C uses the default parameter 100;
anonymous functions and partial functions of Python