python – 嵌套理解中的NameError

参见英文答案 > Accessing class variables from a list comprehension in the class definition                                    2
我有一个文件中的这个代码

class Sudoku(dict):
    COLUMNS = [
        {(x, y) for y in xrange(9)} for x in xrange(9)
    ]

当我运行python broken.py,我得到追溯:

Traceback (most recent call last):
  File "U:\broken.py", line 1, in <module>
    class Sudoku(dict):
  File "U:\broken.py", line 3, in Sudoku
    {(x, y) for y in xrange(9)} for x in xrange(9)
  File "U:\broken.py", line 3, in <setcomp>
    {(x, y) for y in xrange(9)} for x in xrange(9)
NameError: global name 'x' is not defined
[Finished in 0.1s with exit code 1]

我真的不明白这里的问题.理解中是否定义x?

什么陌生人是如何直接粘贴到python解释器中似乎执行没有错误…

编辑:如果我使用列表理解而不是集合理解,这是有效的

我提交了一个错误here.这在python 2.7.5中仍然被设计破坏了.

从错误报告:

In Python 2, list comprehensions don’t have their own scope, so the x in your initial example lives at class scope. However, the set comprehension does have its own scope. By design, a variable defined at class scope is not visible to inner scopes inside that class.

In Python 3, this works because the list comprehension has its own scope.

翻译自:https://stackoverflow.com/questions/12259251/nameerror-in-nested-comprehensions

转载注明原文:python – 嵌套理解中的NameError