0
To illustrate, let’s consider this class statement:
x = 1
class Foo:
a = x
b = [x]
c = [x for _ in range(1)]
print(f'x = {x}') # x = 1
print(f'Foo.a = {Foo.a}') # Foo.a = 1
print(f'Foo.b = {Foo.b}') # Foo.b = [1]
print(f'Foo.c = {Foo.c}') # Foo.c = [1]
See working on Ideone | Repl.it
This shows that during class declaration the value of x
is searched in the global scope, since the scope of the class is not defined. However, if we define a value for x
in the class the output changes:
x = 1
class Foo:
x = 2
a = x
b = [x]
c = [x for _ in range(1)]
print(f'x = {x}') # x = 1
print(f'Foo.a = {Foo.a}') # Foo.a = 2
print(f'Foo.b = {Foo.b}') # Foo.b = [2]
print(f'Foo.c = {Foo.c}') # Foo.c = [1]
See working on Ideone | Repl.it
The values of Foo.a
and Foo.b
use the value of Foo.x
, but the value of Foo.c
continues to consider the x
global.
This behavior occurs because in Foo.c
is used to comprehensilist on? How, in fact, the interpreter manages the scope during the declaration of a class?