Chinaunix首页 | 论坛 | 博客
  • 博客访问: 420041
  • 博文数量: 83
  • 博客积分: 2622
  • 博客等级: 少校
  • 技术积分: 1345
  • 用 户 组: 普通用户
  • 注册时间: 2010-03-17 08:59
个人简介

一直在努力

文章分类

全部博文(83)

文章存档

2014年(3)

2013年(9)

2012年(46)

2010年(25)

分类: Python/Ruby

2013-10-17 18:39:30

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()
阅读(2105) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~