gpt4 book ai didi

python - 为什么列表理解闭包在 python 3 中抛出 `NameError` 但在 python 2 中不抛出?

转载 作者:行者123 更新时间:2023-12-04 15:41:36 25 4
gpt4 key购买 nike

<分区>

在将代码从 Py2 升级到 Py3 时,我遇到了一个我无法解释的怪事。类定义中的列表理解可以引用 python 2 和 3 中的其他类级别变量作为 for 子句的一部分。但是,如果变量是 if 子句的一部分,它们会在 python 3 中抛出一个 NameError 但在 python 2 中工作得很好。

我发现了一些相关问题,但它们似乎并不能很好地解释问题。 Dictionary class attribute that refers to other class attributes in the definition在 lambdas 中是一个类似的问题,但似乎不依赖于 python 版本。另外Why am I getting a NameError in list comprehension (Python)? ,但与调试器而不是类中的范围有关。

以下代码在 python 2.7.16 上运行良好,但在 Python 3.7.4 上运行失败:

class A(object):
a = [1, 2, 3]
b = [n for n in a if n in a]

print(A.b)

在 python 2 中我得到:

[1, 2, 3]

在 python 3 中我得到:

Traceback (most recent call last):
File "list_comprehension_closure.py", line 3, in <module>
class A(object):
File "list_comprehension_closure.py", line 5, in A
b = [n for n in a if n in a]
File "list_comprehension_closure.py", line 5, in <listcomp>
b = [n for n in a if n in a]
NameError: name 'a' is not defined

但是,以下代码在 python 2 和 3 中都可以正常工作,唯一的区别是 if 子句:

class A(object):
a = [1, 2, 3]
b = [n for n in a]

print(A.b)

此外,以下内容在 python 2 和 3 中都有效,唯一的区别是理解是在 class block 之外定义的:

a = [1, 2, 3]
b = [n for n in a if n in a]

print(b)

我知道 Python 3 中的闭包和列表理解有一些变化,但我没有看到任何可以解释这种差异的东西。

编辑:为清楚起见,我不是在寻找解决方法。如上一个示例所示,我知道将变量移出类范围可以解决问题。但是,我正在寻找的是解释为什么在 python 3 中更改了此行为。

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