在 Python 中,class 名称何时绑定? IE。 when/where 我们可以引用 class 名称 w/o 得到一个 `NameError` 吗?

In Python, when does the class name become bound? I.e. when/where can we reference the class name w/o getting a `NameError`?

Python documentation 说:

the following will fail:

class A:
    a = 42
    b = list(a + i for i in range(10))

我 运行 它和它,果然它失败了:它抛出 NameError: name 'a' is not defined。所以我试图通过在 list 参数中使用 A.a 而不是 a 来修复:

class A:
    a = 42
    b = list(A.a + i for i in range(10))

但这仍然没有用。它抛出 NameError: name **'A'** is not defined.

class 名称(在本例中为 A 标识符)何时绑定以便我们可以引用它?我知道在 A 的方法中引用 A 是有效的,因为当 Python 正在解析时? class 定义,它不执行 class 方法。例如,以下工作:

class A:
    a = 42
    # b = list(A.a + i for i in range(10))
    
    def foo(self):
        print(A)

    @classmethod
    def bar(cls):
        print(A)

    @staticmethod
    def baz():
        print(A)

a = A()
a.foo()
a.bar()
a.baz()
在 class 定义块完成之前,

A 不会绑定。引用 tutorial:

When a class definition is left normally (via the end), a class object is created. This is basically a wrapper around the contents of the namespace created by the class definition; we’ll learn more about class objects in the next section. The original local scope (the one in effect just before the class definition was entered) is reinstated, and the class object is bound here to the class name given in the class definition header (ClassName in the example).