yield关键词是python中一个重要的关键字,关于yield的问题是Stack Overflow上最热点的问题。可以用以下代码来感受yield的用法:
def foo():
print("This is before keyword yield")
yield 4
print("This is after keyword yield")
gen = foo()
next(gen)
next(gen)
结果如下:
(most recent call last):
File "E:\python60days\kw_yeild\yeild_test.py", line 7, in <module>
next(gen)
StopIteration
[Finished in 1.0s with exit code 1]
可以看到,我们使用foo的时候并没有马上运行,而是生成了一个gen的生成器。如果需要调用函数中的语句,需要使用next()方法对生成器进行操作,而且我们看到,一但运行到yield关键词位置,类似于return,函数就进行了返回。但是和return不一样的是,再运行一次next方法,函数将从上次返回的位置运行。