yield & send
1. yield只能用在function内部,使得function返回成为一个generator
>>> def h():
... print "hhh"
... yield 5
...
>>> h() #generator
object
>>>h #h属性是function
>>> c=h()
>>> c.send("O") #在没有启动generator之前,不能使用send
Traceback (most recent call last):
File "", line 1, in
TypeError: can't send non-None value to a just-started generator
>>> c.next() #开始执行generator
hhh
5
>>> c.send(6) #只有一个值5,再次next将会抛出
StopIteration异常
Traceback (most recent call last):
File "", line 1, in
StopIteration
>>> help(c) #查看generator的文档描述
| send(...)
| send(arg) -> send 'arg' into generator,
| return next yielded value or raise StopIteration.
send发送给generator参数,作为generator的返回值,并且执行next操作
因为上述函数只有一次yield 5,因此抛出了异常。
其实send(None)效果等同于next()
阅读(2164) | 评论(0) | 转发(0) |