好的,那么有没有办法从函数返回一个值 - 方式return
- 但不停止函数 - 方式return
吗?
我需要这个,所以我可以经常返回值。(延迟由time.sleep()
或其他提供。)
好的,那么有没有办法从函数返回一个值 - 方式return
- 但不停止函数 - 方式return
吗?
我需要这个,所以我可以经常返回值。(延迟由time.sleep()
或其他提供。)
我想你正在寻找yield
. 例子:
import time
def myFunction(limit):
for i in range(0,limit):
time.sleep(2)
yield i*i
for x in myFunction(100):
print( x )
def f():
for i in range(10):
yield i
g = f().next
# this is if you actually want to get a function
# and then call it repeatedly to get different values
print g()
print g()
print
# this is how you might normally use a generator
for i in f():
print i
输出:
0
1
0
1
...
9