Lambda function anonymous function-stack overflow

Lambda anonymous function

Python uses lambda to create anonymous functions.

  • Lambda is just an expression, the function body is much simpler than def.
  • The main 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.
  • Although the lambda function looks like it can only write one line, it is not equivalent to the inline function of C or C ++. The purpose of the latter is to call the small function without occupying stack memory and increase the operating efficiency.

grammar

The syntax of the lambda function contains only one statement, as follows:

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

usage

Its practicality is simple

def sum(x,y):
      return x+y
  
s = lambda x, y : x + y
print(sum(4, 6)) # 输出10
print(s(4, 6)) # 输出10 效果一样

b = lambda x, y, z : (x + 4) * y - z
print(b(1, 2, 3)) # 输出 (1+4) * 2 - 3 == 7 

# 注 : 不带参数时返回的是 lambda函数的地址 一个函数对象
print(b) # 此时输出是函数b的地址 格式如:<function <lambda> at 0x0000000002093E18>

Guess you like

Origin www.cnblogs.com/coderzjz/p/12738409.html