Create anonymous functions in python

1. Use occasions:

In python3, if you want to handle a simple logic function, you can use lambda to create an anonymous function, such as the parameters of a function or the logic of a sentence, etc.

  • lambda is just an expression, and the function body is much simpler than def.
  • The body of a lambda is an expression, not a code block. Only limited logic can be encapsulated in lambda expressions.
  • A lambda function has its own namespace and cannot access parameters outside its own parameter list or in the global namespace.
  • Although it seems that the lambda function can only write one line, it is not equivalent to the inline function of C or C++. The purpose of the latter is to increase the operating efficiency by not occupying the stack memory when calling the small function.

2. Grammar

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

3. Examples of use

1. The anonymous function only passes in two values ​​to realize a simple function of judging the size (ternary expression)

maxx = lambda x,y:x if x>y else y
    print("最大值为:",maxx(10,15))
    print("最大值为:",maxx(20,15))
# >>>最大值为: 15
# >>>最大值为: 20

2. The parameters of anonymous functions have default values

summ = lambda a, b=30: a + b
print('带有默认值:', summ(10))
print('修改默认值:', summ(10, b=1)) 
 
# >>> 带有默认值: 40
# >>> 修改默认值: 11

3. After defining the anonymous function, you can directly add parameter values ​​​​behind to use it directly

summ2 = (lambda x, y: x + y)(3, 4)
print('在函数后添加值:3 + 4 =', summ2)

# >>> 在函数后添加值:3 + 4 = 7

Fourth, the difference between functions and anonymous functions

Ordinary functions can achieve more complex functions, and ordinary functions are more suitable for scenarios where the function needs to be referenced multiple times, and the defined functions can be referenced to other classes;

Anonymous functions can only implement simple logic, and can only be referenced under the current class. In normal programming, anonymous functions (lambda) are mainly used where parameters are to be passed in, and simple judgment functions on the passed parameters

V. Summary

The definition of anonymous functions is much simpler than that of ordinary functions, and it can realize simple logic functions, making the code look more concise and easy to read. Generally, it is only used once and will not be referenced multiple times. In addition, anonymous functions can also be nested and used with decorators.

Guess you like

Origin blog.csdn.net/weixin_46769840/article/details/127336176