2015-12-21 55 views
0

我想將下面的代碼的答案返回給變量,變量應該每5秒更改一次,因此我不能使用'return',因爲它結束了該函數。如何在不結束Python函數的情況下返回變量變量?

例如:

from time import sleep 

def printit(): 
    cpt = 1 
    while True: 
     if cpt < 3: 
      number = ("images[" + str(cpt) + "].jpg") 
      return number #here is the return 
      sleep(5) 
      cpt+=1 
     else: 
      printit() 

answer = printit() 
print(answer) #only 1 answer is printed, then the function ends because of the 'return' 

什麼是解決這一問題的解決方案?

變量答案應每5秒更換一次而不終止該功​​能。

+6

一種用於發電機的工作https://wiki.python.org/moin /發電機或關閉http://www.shutupandship.com/2012/01/python-closures-explained.html?m=1 – dylan7

回答

7

解決此問題的解決方案是什麼?可變回答應該每5秒更換一次而不終止該功​​能。

這裏有一個方法基於generator functions

from time import sleep 

def printit(): 
    cpt = 1 
    while True: 
     if cpt < 3: 
      number = ("images[" + str(cpt) + "].jpg") 
      yield number #here is the return 
      sleep(5) 
      cpt+=1 
     else: 
      for number in printit(): 
       yield number 


for number in printit(): 
    print number 

這將使進程中運行,直到for循環沒有收到更多的價值。要緩慢停止它,您可以發送一個值到發電機:

gen = printit() 
for i, number in enumerate(gen): 
    print i, number 
    if i > 3: 
     try: 
      gen.send(True) 
     except StopIteration: 
      print "stopped" 

對於這項工作,修改yield聲明如下:

(...) 
stop = yield number #here is the return 
if stop: 
    return 
(...) 

取決於你想要達到這可能是什麼或可能無法提供足夠的併發水平。如果您想了解更多關於基於生成器的協同程序的知識,這些非常有見識的論文和David Beazley的視頻是一個特例。

0

如果你想要一個無限的數量,你應該使用itertools.count與發電機的功能,這將允許你簡潔地編寫代碼:

from itertools import count 
from time import sleep 

def printit(): 
    cn = count(1) 
    for i in iter(cn.next, 0): 
     yield "images[{}].jpg".format(i) 
     sleep(5) 

for answer in printit(): 
    print(answer) 
相關問題