我很难理解这个表达式,特别是为什么没有抛出错误,因为在定义lambda时,lambda引用本身只是被声明了。有趣的是,它也以递归的方式工作。我希望L不是定义错误。这可能是因为隐含的变量提升吗?(python将变量声明移至当前范围的顶部/开始)
#why doesn't this throw an error
L = lambda: print(L)
#recursive example...
L = lambda: L()发布于 2018-07-20 09:36:51
#why doesn't this throw an error
L = lambda: print(L)这里您只定义了一个匿名函数并将其地址存储在L中,而不是在这里执行逻辑。您可以将lambda函数赋值给一个变量,以给它命名。正是您在上述代码中所做的工作。
>>> lambda: print(x) <function <lambda> at 0x7f17e201b9d8>
在上面的示例中,可以看到逻辑没有执行,但是返回了一个函数地址。现在,如果我们尝试运行它:
>>> a = lambda: print(x) \>>> a() Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 1, in <lambda> NameError: name 'x' is not defined
您可以看到,一旦我们试图执行逻辑,它就会破坏您所期望的消息。
现在,您的代码没有中断的原因是,一旦它通过调用L()在最后一行执行,L已经被定义为如下所示:
#why doesn't this throw an error
L = lambda: print("Here is the L i defined just in this line: {}".format(L))
>>> L
<function <lambda> at 0x7fc345e4e9d8>
>>> L()
Here is the L i defined just in this line: <function <lambda> at 0x7f6b12ad79d8>
#recursive example...
L = lambda: L()如果我调用L(),就会得到一个递归错误,因为函数一次又一次地调用它
RecursionError:超过最大递归深度
https://stackoverflow.com/questions/51437283
复制相似问题