The Python documentation says:
the following will fail:
class A:
a = 42
b = list(a i for i in range(10))
I ran it and it and sure enough it fails: it throws NameError: name 'a' is not defined
. So I tried to fix by using A.a
instead of a
in the list
argument:
class A:
a = 42
b = list(A.a i for i in range(10))
but that still didn't work. It throws NameError: name **'A'** is not defined
.
When does the class name (in this case the A
identifier) become bound such that we can reference it? I know that referencing A
within a method of A
is valid because when Python is parsing? the class definition, it doesn't execute the class methods. As an example, the following works:
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()
CodePudding user response:
A
is not bound until the class definition block completes. To quote the 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).