gpt4 book ai didi

python 3 : using "all" on class variables

转载 作者:太空宇宙 更新时间:2023-11-04 07:40:36 25 4
gpt4 key购买 nike

下面是一些引发 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 中两者都不会工作。)

关于 python 3 : using "all" on class variables,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22704356/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com