您是否可以使用发送到发电机generator.send https://docs.python.org/3/reference/expressions.html#generator.send?所以,是的,您可以让生成器根据外界的反馈来改变其行为。来自文档:
generator
.send(value)
恢复执行并将一个值“发送”到生成器函数中。
value 参数成为当前yield 表达式的结果。
这send()
方法返回生成器生成的下一个值
[...]
Example
这是一个计数器,只有在被告知这样做时才会递增。
def conditionalCounter(start=0):
while True:
should_increment = yield start
if should_increment:
start += 1
Usage
由于使用 for 循环进行迭代不允许使用generator.send
,你必须使用 while 循环。
import random
def some_calculation_on(value):
return random.choice([True, False])
g = conditionalCounter()
last_value = next(g)
while last_value < 5:
last_value = g.send(some_calculation_on(last_value))
print(last_value)
Output
0
0
1
2
3
3
4
4
5
让它在 for 循环中工作
您可以通过制作一个 for 循环来完成上述工作YieldReceive
class.
class YieldReceive:
stop_iteration = object()
def __init__(self, gen):
self.gen = gen
self.next = next(gen, self.stop_iteration)
def __iter__(self):
return self
def __next__(self):
if self.next is self.stop_iteration:
raise StopIteration
else:
return self.next
def send(self, value):
try:
self.next = self.gen.send(value)
except StopIteration:
self.next = self.stop_iteration
Usage
it = YieldReceive(...)
for x in it:
# Do stuff
it.send(some_result)