Advanced Python (31) – some important features of functions and lambda expressions

Original link: https://chegva.com/5493.html

◎Knowledge points

  1. Some important properties of functions

  2. lambda expression

◎Script practice

▽ Some important features of functions

 """ In python everything is an object. So, functions are also objects, so functions can be assigned to the variable """  def add(num1, num2): return num1 + num2  print(add) # <function add at 0x104eabb80>  f = add print(f(1, 2)) # 3  """ A function can be used as an argument to another function"""  def eval_square(x): return x * x  result = map(eval_square, [1, 2, 3, 4]) print(list(result)) # [1, 4, 9, 16]  """ A function can be used as the return value of another function """  def do_sth(): return add  print(do_sth()(1, 2)) # 3  """ A function can be nested within another function"""  def outer(): def inner(): print("This is inner") return inner  outer()() # This is inner 

lambda expression

 """ The syntax for defining a function is: def function name([formal parameter 1, formal parameter 2, ..., formal parameter n]): function body  When there is only one line of return statement in the function body, the definition of the function can be replaced by a lambda expression whose syntax is: lambda [parameter 1, parameter 2, ..., parameter n]: expression on formal parameters  Compared to the syntactic format for defining functions, lambda expressions: (1) no function name (2) no keyword def (3) No parentheses (4) An expression on a formal parameter is equivalent to the return value of a function  A lambda expression is an anonymous simplified version of a function"""  def add(num1, num2): return num1 + num2  print(add(1, 2)) # 3  print((lambda num1, num2: num1 + num2)(1, 2)) # 3  """ In python everything is an object. So, lambda expressions are also objects, so lambda expressions can be assigned to the variable """  le = lambda num1, num2: num1 + num2 print(le(1, 2)) # 3  """ Because lambda expressions are anonymous and simplified versions of functions, lambda expressions can be used as function arguments"""  result = map(lambda x: x * x, [1, 2, 3, 4]) print(list(result)) # [1, 4, 9, 16]  """ Because lambda expressions are anonymous simplified functions, lambda expressions can be used as the return value of the function """  def do_sth(): return lambda num1, num2: num1 + num2  print(do_sth()(1, 2)) # 3


◎Script address:


This article is reprinted from: https://chegva.com/5493.html
This site is for inclusion only, and the copyright belongs to the original author.