有关Python中的Lambda函数的问题 [英] A question regarding the Lambda function in Python

查看:79
本文介绍了有关Python中的Lambda函数的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么在以下代码中输出为22?

Why in the following code, the output is 22?

据我所知,我们有一个需要两个参数的函数,但是仅使用一个参数就定义了它!但是,第一次在 mydoubler = myfunc(2)中使用它时,它将参数(2)分配给变量 n ,但是第二次在 print(mydoubler(11),它使用参数(11)设置变量 a 的值!为什么呢?Lambda是否像递归函数一样工作?

In my understanding, we have a function that needs two arguments, but it has been defined with only one! However, the first time we use it in mydoubler = myfunc(2), it assigns the argument(2) to variable n, but the second time we use it in print(mydoubler(11), it uses the argument(11) to set the value of the variable a! Why is that? Does Lambda work like a recursive function?

   def myfunc(n):
        return lambda a : a * n

   mydoubler = myfunc(2)

   print(mydoubler(11))

推荐答案

基本上会发生什么:

mydoubler = myfunc(2)实际上与编写 mydoubler = lambda a:a * 2

这样做的原因是 myfunc(2)返回 lambda a:a * 2

所以现在 mydoubler = lambda a:a * 2

然后,当调用 mydoubler(11)时,它仅返回 11 * 2

Then when mydoubler(11) is called, it simply returns 11 * 2

这篇关于有关Python中的Lambda函数的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆