[英]Will the function in python for loop be executed multiple times?
假設我有一個返回列表的方法的以下類:
Class C():
def f():
return [1,2,3]
如果我循環這個方法如下:
c=C()
for i in c.f():
print i
在for循環中,cf()會被執行多次嗎? 如果是,為了得到它一次,我是否必須在循環之外做任務,或者有一些微不足道的方法?
In [395]: def tester():
...: print "Tester Called!"
...: return [1,2,3]
In [396]: for i in tester():
...: pass
Tester Called!
似乎答案是否定的。
cf()
不會多次執行。
你沒有問,但你可能對發電機很好奇。
您作為生成器的示例如下:
Class C():
def f():
yield 1
yield 2
yield 3
迭代結果的循環將保持不變。
來自python文檔 :
for語句用於迭代序列的元素(例如字符串,元組或列表)或其他可迭代對象:
for_stmt ::= "for" target_list "in" expression_list ":" suite ["else" ":" suite]
表達式列表評估一次 ; 它應該產生一個可迭代的對象。
不,它被執行一次 。
並且您的方法未正確定義。 應該有一個self
論點:
class C:
def f(self):
return [1,2,3]
它只會被執行一次。 但是代碼中會出現語法錯誤:
class
,而不是上課
def f(self)
,而不是def f()
你有沒有嘗試自己測試一下? 你的問題的答案是否定的。
這是你應該如何測試它。 此外,您的代碼中存在許多缺陷。 檢查下面的自評注修改版本
>>> class C: #its class not Class and C not C()
def f(self): #You were missing the self argument
print "in f" #Simple Test to validate your query
return [1,2,3]
>>> c=C()
>>> for i in c.f():
print i
in f
1
2
3
>>>
雖然這個例子很簡單,但我仍然會以此為例來解釋我們如何利用Python 函數式編程的強大功能 。 我將嘗試解釋的是懶惰評估或生成器函數(http://docs.python.org/glossary.html#term-generator)。
考慮修改后的例子
>>> class C: #its class not Class and C not C()
def f(self): #You were missing the self argument
print "in f" #Simple Test to validate your query
for i in [1,2,3]:
yield i #Generates the next value when ever it is requsted
return #Exits the Generator
>>> c=C()
>>> for i in c.f():
print i
in f
1
2
3
>>>
您看得出來差別嗎?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.