如何在不定义函数的情况下称呼lambda?
对于以下代码中的lambda函数,
def myfunc(n):
return lambda a : a * n
mydoubler = myfunc(2)
print(mydoubler(11))
我试图理解为什么myDoubleer
变成< class'function'>
以及如何调用myDoubler(11)
而无需将其定义为函数。
For lambda functions in the following code,
def myfunc(n):
return lambda a : a * n
mydoubler = myfunc(2)
print(mydoubler(11))
I am trying to understand why mydoubler
becomes <class 'function'>
and how I can call mydoubler(11)
without defining it as a function.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
lambda
是一个函数,但只有一个表达式(代码行)。调用函数并返回结果时执行该表达式。
因此,此lambda的等效:
此
def
函数:您可以阅读更多在这里
A
lambda
is a function, but with only one expression (line of code).That expression is executed when the function is called, and the result is returned.
So the equivalent of this lambda:
is this
def
function:You can read more here
lambda是一个函数,因此您的代码正在执行类似于
您在问如何调用
myDoubler
而无需将其定义为函数的事情,这不是最明显的问题,但是您可以在不命名的情况下调用它就像这样A lambda is a function, so your code is doing something like
You're asking how to call
mydoubler
without defining it as a function, which isn't the clearest question, but you can call it without naming it like so您的
myFunc
正在返回lambda。 Lambda是一个小的匿名功能。 Lambda可以采用任何数量的参数,但只能有一个表达式。因此,执行第三行后,您的
myDoubleer
将成为lambda,这就是为什么尝试print(type(myDoubler))
时,它将返回&lt; class''功能'&gt;
。同样,为了用11调用
myDoubler
,它必须是函数。Your
myfunc
is returning a lambda. Lambda is a small anonymous function. A lambda can take any number of arguments, but can only have one expression.So after execution of the 3rd line, your
mydoubler
will become a lambda that's why when you tryprint(type(mydoubler))
it will return<class 'function'>
.Also in order to call
mydoubler
with 11, it must be function.lambda表达式(例如
def
语句)定义了函数。您的代码可以等效地写成是因为内部函数足够简单,可以将其定义为单个表达式,使用lambda表达式可以为您节省提出其他未使用的名称的麻烦,
def> def
语句要求。这里的关键是内部函数关闭
n
的值该参数传递给myFunc
。也就是说,myDoubler
是用2个乘数乘以2的,而不是任何值n
可能会稍后再进行。 (的确,封闭的目的是创建内部函数使用的 new 变量n
,该功能无法轻易从外部myFunc 。)
A lambda expression, like a
def
statement, defines functions. Your code could be equivalently written asBecause the inner function is simple enough to be defined as a single expression, using a lambda expression saves you the trouble of coming up with the otherwise unused name the
def
statement requires.The key here is that the inner function closes over the value of
n
, so that the function returned bymyfunc
retains a reference to the value of the argument passed tomyfunc
. That is,mydoubler
is hard-coded to multiply its argument by 2, rather than whatever valuen
may get later. (Indeed, the purpose of the closure is to create a new variablen
used by the inner function, one which cannot easily be changed from outsidemyfunc
.)使用装饰器您可以实现此
输出
2422
using decorator you can achive this
output
2422
你的意思是吗?
Do you mean this?