I think that I know how variables and generators work in Python well.
However, the following code makes me confused.
from __future__ import print_function
class A(object):
x = 4
gen = (x for _ in range(3))
a = A()
print(list(a.gen))
When run the code (Python 2), it says:
Traceback (most recent call last):
File "Untitled 8.py", line 10, in <module>
print(list(a.gen))
File "Untitled 8.py", line 6, in <genexpr>
gen = (x for _ in range(3))
NameError: global name 'x' is not defined
In Python 3, it says NameError: name 'x' is not defined
but, when I run:
from __future__ import print_function
class A(object):
x = 4
lst = [x for _ in range(3)]
a = A()
print(a.lst)
The code doesn't work in Python 3, but it does in Python 2, or in a function like this
from __future__ import print_function
def func():
x = 4
gen = (x for _ in range(3))
return gen
print(list(func()))
This code works well in Python 2 and Python 3 or on the module level
from __future__ import print_function
x = 4
gen = (x for _ in range(3))
print(list(gen))
The code works well in Python 2 and Python 3 too.
Why is it wrong in class
?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…