def myfunc(n):
return lambda a : a * n
mytripler = myfunc(3)
print(mytripler(11))我正在尝试学习python中的lambda函数。我理解w3schools中给出的关于Lambda函数的其他例子。这个例子,然而,我不能绕我的头。怎样才能把3乘以11?
发布于 2022-01-29 01:34:14
注意,lambda没有什么特别之处。这只是创建匿名函数的一种方便的方法。
如果已经编写了代码:
def myfunc(n):
def inner(a):
return a * n
return inner这将是完全一样的事情。但是现在我们给匿名函数取了一个名为inner的名字。但是您会发现仍然可以编写mytripler = myfunc(3),而且它的工作方式也是一样的。
Python理解闭包。如果在内部函数中使用了变量(但没有修改),并且在包含函数中定义了同名变量,那么Python就会意识到,内部变量指的是外部变量具有的任何值。
发布于 2022-02-06 19:53:28
让我们退一步:什么是函数?
一个定义可能是这样一个构造:给它参数,它做一些事情,然后返回一个值(让我们暂时忽略不提供任何参数或不接收任何返回值的情况)。
在Python中,因为所有东西都是一个对象,所以这种构造是一个可以指定名称的值。例如:
>>> def example_function(argument):
... result = argument * 42
... return result
...
>>> other_name_for_example_function = example_function
>>> example_function(3)
126
>>> other_name_for_example_function(3)
126
>>> example_function == other_name_for_example_function
True
>>> example_function is other_name_for_example_function
True注意,在最后进行的比较中,我没有调用这些函数,我只是比较了example_function和other_name_for_example_function的值,它们在本例中是相同的“功能机制”。
现在,lambdas是另一种定义函数的方法,但它更受限制,而且函数不会自动分配名称。让我们以相同的例子为例,但使用lambdas:
>>> example_lambda = lambda argument: argument * 42
>>> other_name_for_example_lambda = example_lambda
>>> example_lambda(3)
126
>>> other_name_for_example_lambda(3)
126
>>> example_lambda == other_name_for_example_lambda
True
>>> example_lambda is other_name_for_example_lambda
True现在,如果我们将示例的函数调用替换为其内容,则如下所示:
>>> n = 3 # just you see where that value will be used
>>> mytripler = lambda a: a * n
>>> a = 11 # also to see where that value will be used
>>> mytripler(a)
33所以在你的例子中,
myfunc()提供了一个“函数机制”作为返回值。在“功能机制”的定义中,插入了值3,这是myfunc()mytripler赋给返回的中一样。
这能帮你理解吗?
https://stackoverflow.com/questions/70901569
复制相似问题