Python Lambda 行为
我正在尝试了解 Python 中的 lambda 表达式、闭包和作用域。为什么程序不会在第一行崩溃?
>>> foo = lambda x: x + a
>>> foo(2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in <lambda>
NameError: global name 'a' is not defined
>>> a = 5
>>> foo(2)
7
>>>
I'm trying to get my head around lambda expressions, closures and scoping in Python. Why does the program not crash on the first line here?
>>> foo = lambda x: x + a
>>> foo(2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in <lambda>
NameError: global name 'a' is not defined
>>> a = 5
>>> foo(2)
7
>>>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
因为 Python 函数不是这样工作的;这对 lambda 来说并不特殊:
变量在使用时查找,而不是在定义函数时查找。甚至每次调用函数时都会查找它们,如果您有 C 背景(例如),您肯定会发现意外,但这在 Python 中不是问题。
Because that's just not how Python functions work; it's not special to lambdas:
Variables are looked up when used, not when a function is defined. They are even looked up each time the function is called, which you will definitely find unexpected if you're coming from a C background (for example), but this isn't a problem in Python.
在您调用 lambda 表达式之前,它不会被求值。
它确实被解析,这就是语法错误会导致回溯的原因。
Your lambda expression doesn't get evaluated until you call it.
It does get parsed, which is why a syntax error would cause a traceback.
Python 中的变量可以在设置之前使用。这将生成运行时错误,而不是语法错误。这是一个使用局部变量的示例:
这与将取消引用未分配或未定义的变量视为语法错误的语言形成鲜明对比。 Python 不会“捕获”词法作用域的当前状态,它只是使用对可变词法作用域的引用。这是一个演示:
Variables in Python may be used before they are set. This will generate a runtime error, not a syntax error. Here's an example using local variables:
This is in contrast to languages which consider dereferencing an unassigned or undefined variable a syntax error. Python doesn't "capture" the current state of lexical scope, it just uses references to mutable lexical scopes. Here's a demonstration:
Python 中的 lambda(以及用 def 定义的函数)的主体在被调用之前不会被求值。名称总是在运行时查找。
The bodies of lambdas (and functions defined with def) in Python are not evaluated until they are called. Names are always looked up at runtime.
在第一行创建表达式,这与评估它不同。当您尝试评估它时,它会找不到符号 a 。
on the first line you create expression, which is different from evaluating it. When you try to evaluate it, this is then it cannot find symbol a .