maple412 发表于 2014-12-15 11:38

yield的使用疑问

def counter(start=0):
    count=start
    while True:
      val=(yield count)
      count+=1

执行如下:
>>> c.next()
5
>>> c.next()
6
>>> c.send(10)
7
>>> c.next()
8
执行c.send(10)之后,预期应该是输出11的,但是还是按照加一的输出
程序改成如下后,输出正常
def counter(start=0):
    count=start
    while True:
      val=(yield count)
      if val is not None:
            count=val
      else:
            count+=1

对yield语句有几点疑问,
1 if val is not None,val这个参数应该是一直不为None的,那么就应该进入count=val而不是count+=1
2 为什么之前的程序执行c.send()后不生效?

Linux_manne 发表于 2014-12-15 15:29

来自官方的
When a generator function is resumed with a next() method, the current yield expression always evaluates to None.

maple412 发表于 2014-12-17 10:31

回复 2# Linux_manne

1 意思是说只要调用了.next(),那么 val=(yield count) 这个语句val的值都是None?
2为什么之前的程序执行c.send()后不生效?这个是什么原因呢
   
页: [1]
查看完整版本: yield的使用疑问