Note on Resolution of Names in 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.
You have declared a variable ID
inside the class definition that makes it an class
or static
variable. So its scope is limited the to class block, and hence you can't access it inside the comprehensions
.
you can read more about it at python docs
Consider the examples,
Example #1:
class A:
ID = "This is class A."
print(ID)
Now when you execute >>>A()
the output will be This is class A
which is totally fine because the scope of variable ID
is limited to class A
Example #2:
class B:
L = [ 1, 2, 3, 4, 5, 6, 7]
print([i * 2 for i in L])
Now when you execute >>>B()
the output will be [2, 4, 6, 8, 10, 12, 14]
which is totally fine because the scope of list L
is limited to class B
Example #3:
class C:
L = [ 1, 2, 3, 4, 5, 6, 7]
print([L[i] * 2 for i in range(7)])
Now executing >>>C()
will raise a NameError
stating that name L
is not defined.