Python中yield表达式的结果是什么? [英] What is the result of a yield expression in Python?
问题描述
我知道yield将函数转换为生成器,但是yield表达式本身的返回值是多少?例如:
I know that yield turns a function into a generator, but what is the return value of the yield expression itself? For example:
def whizbang():
for i in range(10):
x = yield i
该函数执行时变量x
的值是什么?
What is the value of variable x
as this function executes?
我已阅读Python文档: http://docs. python.org/reference/simple_stmts.html#grammar-token-yield_stmt ,似乎没有提及yield表达式本身的值.
I've read the Python documentation: http://docs.python.org/reference/simple_stmts.html#grammar-token-yield_stmt and there seems to be no mention of the value of the yield expression itself.
推荐答案
您还可以send
值生成器.如果未发送任何值,则x
为None
,否则x
接受发送的值.这里是一些信息: http://docs.python. org/whatsnew/2.5.html#pep-342-new-generator-features
You can also send
values to generators. If no value is sent then x
is None
, otherwise x
takes on the sent value. Here is some info: http://docs.python.org/whatsnew/2.5.html#pep-342-new-generator-features
>>> def whizbang():
for i in range(10):
x = yield i
print 'got sent:', x
>>> i = whizbang()
>>> next(i)
0
>>> next(i)
got sent: None
1
>>> i.send("hi")
got sent: hi
2
这篇关于Python中yield表达式的结果是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!