【发布时间】:2017-04-12 10:29:21
【问题描述】:
我认为我很了解变量和生成器在 Python 中的工作原理。
但是,下面的代码让我很困惑。
from __future__ import print_function
class A(object):
x = 4
gen = (x for _ in range(3))
a = A()
print(list(a.gen))
运行代码时(Python 2),它说:
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
在 Python 3 中,它表示 NameError: name 'x' is not defined
但是,当我跑步时:
from __future__ import print_function
class A(object):
x = 4
lst = [x for _ in range(3)]
a = A()
print(a.lst)
该代码在 Python 3 中不起作用,但在 Python 2 或类似的函数中起作用
from __future__ import print_function
def func():
x = 4
gen = (x for _ in range(3))
return gen
print(list(func()))
此代码在 Python 2 和 Python 3 或模块级别上运行良好
from __future__ import print_function
x = 4
gen = (x for _ in range(3))
print(list(gen))
该代码在 Python 2 和 Python 3 中也能正常运行。
为什么class会出错?
【问题讨论】:
标签: python variables generator