【发布时间】:2016-08-28 01:58:26
【问题描述】:
我在 python 3 中尝试使用生成器并编写了这个相当做作的生成器:
def send_gen():
print(" send_gen(): will yield 1")
x = yield 1
print(" send_gen(): sent in '{}'".format(x))
# yield # causes StopIteration when left out
gen = send_gen()
print("yielded {}".format(gen.__next__()))
print("running gen.send()")
gen.send("a string")
输出:
send_gen(): will yield 1
yielded 1
running gen.send()
send_gen(): sent in 'a string'
Traceback (most recent call last):
File "gen_test.py", line 12, in <module>
gen.send("a string")
StopIteration
所以gen.__next__() 到达x = yield 1 行并产生1。我认为x 将分配给None,然后gen.send() 将寻找下一个 yield 语句因为x = yield 1 被“使用”了,然后得到一个StopIteration。
相反,似乎发生的事情是x被发送“一个字符串”,它被打印出来,然后然后python尝试寻找下一个@ 987654332@ 并获得StopIteration。
所以我试试这个:
def send_gen():
x = yield 1
print(" send_gen(): sent in '{}'".format(x))
gen = send_gen()
print("yielded : {}".format(gen.send(None)))
输出:
yielded : 1
但现在没有错误。在将x 分配给None 之后,send() 似乎没有尝试查找 next yield 语句。
为什么行为略有不同?这与我如何启动生成器有关吗?
【问题讨论】:
标签: python python-3.x generator yield coroutine