Python Lambda 行为

5 投票
5 回答
6433 浏览
提问于 2025-04-15 19:28

我正在努力理解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
>>> 

5 个回答

2

你的lambda表达式在你调用它之前是不会被计算的。

它确实会被解析,所以如果有语法错误,就会出现错误追踪信息。

>>> foo = lambda x : x + a
>>> bar = lambda y : print y
SyntaxError: invalid syntax
2

在Python中,你可以在给变量赋值之前就使用它。这会导致运行时错误,而不是语法错误。下面是一个使用局部变量的例子:

>>> def f():
...     return a
...     a = 3
... 
>>> f()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in f
UnboundLocalError: local variable 'a' referenced before assignment

这和一些编程语言不同,那些语言会把使用一个未赋值或未定义的变量当作语法错误。Python并不会“捕捉”当前的词法作用域状态,它只是使用对可变词法作用域的引用。下面是一个演示:

>>> def f(): return a
... 
>>> f()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 1, in f
NameError: global name 'a' is not defined
>>> a = 3
>>> f()
3
6

因为这就是Python函数的工作方式;这并不是只有在使用lambda(匿名函数)时才这样:

>>> 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

在使用变量的时候,Python会去查找它们,而不是在定义函数的时候就查找。每次调用这个函数时,Python都会去查找变量,这对于习惯了C语言的人来说可能会感到意外,但在Python中这并不是问题。

撰写回答