# 匿名函数:通俗理解使用lambda关键字定义的函数称为匿名函数,也就是没有名字的函数。
# 匿名函数的特点:
# 1. 匿名函数只能写一行代码
# 2. 匿名函数的返回值不需要加return
# 3. 匿名函数也属于函数
# 匿名函数的语法格式:
# lambda 形参1,形参2,...:返回值或者调用其他函数
def sum_value(n1,n2):
return n1+n2
result = sum_value(1,2)
print(result)
# 使用匿名函数对以上代码简化,使用new_func保存了一下匿名函数。new_func本质上就成为了一个函数。
# 函数的类型就是function,在这里就可以证明匿名函数,
new_func = lambda x,y:x+y
匿名函数的调用也需要加小括号
result = new_func(1,2)
print(new_func, type(new_func)
函数定义的流程:
先回到函数定义的地方,然后给形参赋值,然后执行函数;里面的功能代码,执行结束后回到匿名函数调用的地方。
扩展:没有参数没有返回值的函数2
current_func = lambda: print(“hhaha,我是一个无参数无返回值的匿名函数”)
current_func()
注意点:匿名函数只能实现一些简单的功能,不能实现复杂的功能,比如实现for循环,while循环。