如何在不结束Python函数的情况下返回更改变量?

时间:2015-12-21 18:52:01

标签: python python-3.x

我正在尝试将下面代码的答案返回到变量中,变量应该每5秒更改一次因此我不能使用'return',因为它结束了函数。

示例:

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秒更改一次而不会结束此功能。

2 个答案:

答案 0 :(得分: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这些非常有见地的论文和视频是一个宝库。

答案 1 :(得分: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)