【发布时间】:2016-01-07 06:14:54
【问题描述】:
我无法从yield fromexpression 中找到任何返回值示例。我试过这个简单的代码,但没有成功:
def return4():
return 4
def yield_from():
res = yield from range(4)
res = yield from return4()
def test_yield_from():
for x in yield_from():
print(x)
test_yield_from()
产生:
» python test.py
0
1
2
3
Traceback (most recent call last):
File "test.py", line 52, in <module>
test_yield_from()
File "test.py", line 48, in test_yield_from
for x in yield_from():
File "test.py", line 44, in yield_from
res = yield from return4()
TypeError: 'int' object is not iterable
但我期待:
» python test.py
0
1
2
3
4
因为,正如 PEP 中所述:
此外,当迭代器是另一个生成器时,允许子生成器执行带有值的 return 语句,该值成为 yield from 表达式的值。
显然,我没有得到这个解释。关于yield from,“子生成器”中的return 是如何工作的?
【问题讨论】:
-
我不知道。我正在尝试它,因为我没有找到任何示例。这就是我在这里问的原因,很明显。
标签: python python-3.x yield-from