一面问到的问题。做个记录。
send和next要结合yield一起看:https://blog.csdn.net/qq_21210467/article/details/82873870
def MyGenerator():
value = (yield 10)
value = (yield value)
gen = MyGenerator()
print(next(gen))
print (gen.send(2))
输出结果:
10
2
解析:
send:Resumes the generator and "sends" a value that becomes the result of the current yield-expression.
就是说 这里yield 1整体被视为一个表达式,你send的内容会作为这个表达式的值,随便你左边用什么东西接收或者不接收,总之yield就是你send进来的那个东西。这个表达式变成你send进来后的东西后继续执行,再次遇到yield,输出yield后面跟着的表达式。这部分转自:https://blog.csdn.net/qq_38604641/article/details/71798019
python3.x里面。生成器的next调用是next(对象名)的方式,而在python2.x中是对象名