该楼层疑似违规已被系统折叠 隐藏此楼查看此楼
def subgen():
t = yield
raise StopIteration(t)
def gen():
r = yield from subgen()
print('The returned result is', r)
g = gen()
next(g)
g.send('I got it.')
运行结果:
python.exe F:/python/fluentpython/test/yieldfrom1.py
Traceback (most recent call last):
File "F:/python/fluentpython/test/yieldfrom1.py", line 3, in subgen
raise StopIteration(t)
StopIteration: I got it.The above exception was the direct cause of the following exception:Traceback (most recent call last):
File "F:/python/fluentpython/test/yieldfrom1.py", line 13, in
g.send('I got it.')
File "F:/python/fluentpython/test/yieldfrom1.py", line 7, in gen
r = yield from subgen()
RuntimeError: generator raised StopIterationProcess finished with exit code 1
为什么在subgen中显式抛出StopIteration之后,在gen的yield from subgen()处会抛出RuntimeError,而不是将t赋值给r?而通过用return语句隐式抛出StopIteration之后,可以将t赋值给r?如下:
def subgen():
t = yield
return t
def gen():
r = yield from subgen()
print('The returned result is', r)
g = gen()
next(g)
g.send('I got it.')
运行结果:
python.exe F:/python/fluentpython/test/yieldfrom1.py
The returned result is I got it.
Traceback (most recent call last):
File "F:/python/fluentpython/test/yieldfrom1.py", line 14, in
g.send('I got it.')
StopIterationProcess finished with exit code 1