我正在阅读Python食谱,目前我正在研究发电机.我发现很难理解我的头脑.
因为我来自Java背景,是否有Java等价物?这本书讲的是"制片人/消费者",但是当我听到我想到线程时.
什么是发电机,为什么要使用它?显然没有引用任何书籍(除非你能直接从书中找到一个体面的,简单的答案).也许有例子,如果你感觉很慷慨!
我无法理解这种send方法.我知道它用于操作发电机.但语法在这里:generator.send(value).
我莫名其妙地无法理解为什么值应该成为当前yield表达式的结果.我准备了一个例子:
def gen():
for i in range(10):
X = yield i
if X == 'stop':
break
print("Inside the function " + str(X))
m = gen()
print("1 Outside the function " + str(next(m)) + '\n')
print("2 Outside the function " + str(next(m)) + '\n')
print("3 Outside the function " + str(next(m)) + '\n')
print("4 Outside the function " + str(next(m)) + '\n')
print('\n')
print("Outside the function " + str(m.send(None)) + '\n') # Start generator …Run Code Online (Sandbox Code Playgroud)