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

Hir*_*uri 0 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'
Run Code Online (Sandbox Code Playgroud)

解决此问题的解决方案是什么?

变量答案应每5秒更改一次而不结束该功能.

mir*_*ixx 7

解决此问题的解决方案是什么?变量答案应每5秒更改一次而不结束该功能.

这是一种基于发电机功能的方法

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
Run Code Online (Sandbox Code Playgroud)

这将使进程保持运行,直到for循环不再接收到值.要正常停止它,您可以将值发送到生成器:

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

为此,修改yield语句如下:

(...)
stop = yield number #here is the return
if stop:
   return
(...)
Run Code Online (Sandbox Code Playgroud)

根据您想要实现的目标,这可能会或可能不会提供足够的并发级别.如果你想了解更多关于基于生成器的协同程序的知识,David Beazley的这些非常有见地的论文和视频是一个宝库.