易百教程

96、Python 中的 yield 关键字有什么作用?

yield 关键字可以将任何函数变成生成器,它就像一个标准的return关键字。但它总是会返回一个生成器对象。 此外,一个方法可以多次调用 yield 关键字。

请参见下面的示例:

def testgen(index):
  weekdays = ['sun','mon','tue','wed','thu','fri','sat']
  yield weekdays[index]
  yield weekdays[index+1]

day = testgen(0)
print next(day), next(day)

#output: sun mon