我试图了解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
>>> 
小智 6
因为这不是Python功能的工作方式; 对lambdas来说并不特别:
>>> def foo(x):
...   return x + a
>>> foo
<function foo at 0xb7dde454>
>>> foo(2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in foo
NameError: global name 'a' is not defined
使用时会查找变量,而不是在定义函数时查找变量.每次调用函数时都会查找它们,如果你来自C背景(例如),你肯定会发现意外,但这在Python中不是问题.