我認爲我知道變量和生成器如何在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
錯?
聲明'它是在類之外執行的(因爲生成器在運行時被評估)並且在當前範圍**中檢查x **的引用可能有爭議。看到這個http://ideone.com/bgef81結果是[6,6,6],而不是[5,5,5],爲什麼? – WeizhongTu