NameError 在理解中引用 class 个变量

NameError referencing class variables in comprehension

我在尝试访问字典理解中的 class 变量时得到 NameError: name 'ID' is not defined,例如在 class A。在没有理解的情况下引用时它工作正常(参见 class B)。所以我的问题是,为什么它在 class A 而不是在 class B 中抛出 NameError?

class A:
    ID = "This is class A."

    test = {str(i): ID for i in range(5)}

class B:
    ID = "This is class B."

    test = f"{ID}"

关于 Python 中名称解析的说明:

Class definition blocks and arguments to exec() and eval() are special in the context of name resolution. A class definition is an executable statement that may use and define names. These references follow the normal rules for name resolution with an exception that unbound local variables are looked up in the global namespace. The namespace of the class definition becomes the attribute dictionary of the class. The scope of names defined in a class block is limited to the class block; it does not extend to the code blocks of methods – this includes comprehensions and generator expressions since they are implemented using a function scope. This means that the following will fail.

您在 class 定义中声明了一个变量 ID,使其成为 classstatic 变量。所以它的 范围被限制在 class 块 ,因此你不能在 comprehensions.

中访问它

您可以在 python docs

阅读更多相关信息

考虑示例,

示例 #1:

class A:
    ID = "This is class A."
    print(ID)

现在,当您执行 >>>A() 时,输出将是 This is class A,这完全没问题,因为变量 ID 的范围被限制为 class A


示例 #2:

class B:
    L = [ 1, 2, 3, 4, 5, 6, 7]
    print([i * 2 for i in L])

现在,当您执行 >>>B() 时,输出将是 [2, 4, 6, 8, 10, 12, 14],这完全没问题,因为列表 L 的范围限于 class B


示例 #3:

class C:
   L = [ 1, 2, 3, 4, 5, 6, 7]
   print([L[i] * 2 for i in range(7)])

现在执行 >>>C() 将引发一个 NameError 说明名称 L 未定义。