为什么第二个next
不会返回"bye"
?
def salute():
yield "hello"
yield "bye"
def greet_me():
print(next(salute()))
print(next(salute()))
greet_me()
输出:
你好
您好
答案 0 :(得分:6)
因为您每次拨打salute()
时都要创建新生成器。创建生成器一次然后然后调用它上面的next
以获得两个产量以产生它们的值:
def greet_me():
gen = salute() # create the generator
print(next(gen)) # start it, goes to the first yield
print(next(gen)) # resume it, goes to second yield
现在,调用greet_me
会打印预期结果。