下面是一些引发 NameError 的代码:
class Foo:
a = [1,2,3,4,5]
b = all(i for i in a) # works fine !
c = [2,3,4]
d = all(i in a for i in c) # raises NameError : name 'a' is not defined
我对此很困惑 --;
谢谢!
请您参考如下方法:
参见 this previous question , 相似但不相同。
如该回答所述:
classes don't have a lexical scope (actually, in either Python 2 or Python 3). Instead, they have a local namespace that does not constitute a scope. This means that expressions within the class definition have access to the content of the namespace [...] but scopes introduced within the body of the class do not have access to its namespace
在生成器表达式中,for 子句位于封闭范围/命名空间中,但目标表达式位于生成器表达式创建的新范围中。此新作用域无权访问封闭类作用域。
简而言之,您的示例工作和失败的原因与此工作的原因相同:
class Foo(object):
a = 2
def method(self, x=a):
print x
但这失败了:
class Foo(object):
a = 2
def method(self, x):
print a
生成器表达式的 for 子句在作用域上类似于方法的参数规范:它在封闭的命名空间中执行。但 genexp 的目标表达式类似于方法体:它在自己的范围内执行,无法访问类命名空间。
(在 Python 2 中,使用列表推导式而不是生成器推导式会起作用,因为列表推导式不会在 Python 2 中创建新的范围。这被认为是一个缺陷并在 Python 3 中进行了更改,因此在 Python 3 中两者都不会工作。)
