yield 函数回调 1:举个例子, def test(): print 'yield test 1' yield 1 test() 运行之后没有输出结果! 原因: 包含了关键字"yield"的函数就不是普通的函数。当含有这个关键字的函数被调用的时候,这个函数在遇到yield的时候会停止运行,并且返回一个迭代器(iterator)。每次请求一个值,就会执行生成的代码。直到遇到一个yield或者return。 def test(): print 'yield test 1' yield 1 c = test() c.next() 这是就会输出 yield 12: 刚才提到了迭代器的概念(下面是它的内部实现原理): lst=[1,2,3,4,5] for i in lst
print i 从这个例子我们可以看的出来,每循环一次i的值就会指向列表的下一个元素,大家认为这是正常的,那么为什么i会得到列表的下一个元素呢?
其实在for的循环中列表就使用了迭代器。每一次循环迭代器就使用next方法返回一个值。当然这个迭代是隐形的,大家是看不见的。
我们可以实现一个可迭代的函数。 #!/ust/bin/env python class IterExample():
def __init__(self):
self.a = 0
def next(self):
self.a += 1
if self.a > 10: raise StopIteration
return self.a
def __iter__(self):
return self ie = IterExample() for i in ie:
print i 3: yield的原理探索 其实这个很简单。只不过大家看的例子复杂了。看看下面的例子你立刻就会理解它。 count = 0 count += 1 print 'count', count enter 1 count 1 next 2 count 2 next again 我来解释一下这个程序: 4: yield 的原理 4.1 yield是一个表达式Python2.5以前,yield是一个语句,但现在2.5中,yield是一个表达式(Expression),比如:m = yield 5 表达式(yield 5)的返回值将赋值给m,所以,认为 m = 5 是错误的。那么如何获取(yield 5)的返回值呢?需要用到后面要介绍的send(msg)方法。4.2. 透过next()语句看原理现在,我们来揭晓yield的工作原理。我们知道,我们上面的h()被调用后并没有执行,因为它有yield表达式,因此,我们通过next()语句让它执行。next()语句将恢复Generator执行,并直到下一个yield表达式处。比如:def h(): c.next()调用后,h()开始执行,直到遇到yield 5,因此输出结果:print 'Wen Chuan' yield 5 print 'Fighting!' c = h() c.next() Wen Chuan 当我们再次调用c.next()时,会继续执行,直到找到下一个yield表达式。由于后面没有yield了,因此会拋出异常: Wen Chuan Fighting! Traceback (most recent call last): File "/home/evergreen/Codes/yidld.py", line 11, in <module> c.next() StopIteration 4.3. send(msg) 与 next()了解了next()如何让包含yield的函数执行后,我们再来看另外一个非常重要的函数send(msg)。其实next()和send()在一定意义上作用是相似的,区别是send()可以传递yield表达式的值进去,而next()不能传递特定的值,只能传递None进去。因此,我们可以看做c.next() 和 c.send(None) 作用是一样的。 来看这个例子: def h(): 输出的结果为:print 'Wen Chuan', m = yield 5 # Fighting! print m d = yield 12 print 'We are together!' c = h() c.next() #相当于c.send(None) c.send('Fighting!') #(yield 5)表达式被赋予了'Fighting!' Wen Chuan Fighting! 需要提醒的是,第一次调用时,请使用next()语句或是send(None),不能使用send发送一个非None的值,否则会出错的,因为没有yield语句来接收这个值。 4.4. send(msg) 与 next()的返回值send(msg) 和 next()是有返回值的,它们的返回值很特殊,返回的是下一个yield表达式的参数。比如yield 5,则返回 5 。到这里,是不是明白了一些什么东西?本文第一个例子中,通过for i in alist 遍历 Generator,其实是每次都调用了alist.Next(),而每次alist.Next()的返回值正是yield的参数,即我们开始认为被压进去的东东。我们再延续上面的例子:def h(): 输出结果:print 'Wen Chuan', m = yield 5 # Fighting! print m d = yield 12 print 'We are together!' c = h() m = c.next() #m 获取了yield 5 的参数值 5 d = c.send('Fighting!') #d 获取了yield 12 的参数值12 print 'We will never forget the date', m, '.', d Wen Chuan Fighting! We will never forget the date 5 . 12 4.5. throw() 与 close()中断 Generator中断Generator是一个非常灵活的技巧,可以通过throw抛出一个GeneratorExit异常来终止Generator。Close()方法作用是一样的,其实内部它是调用了throw(GeneratorExit)的。我们看:def close(self): 因此,当我们调用了close()方法后,再调用next()或是send(msg)的话会抛出一个异常:try: self.throw(GeneratorExit) except (GeneratorExit, StopIteration): pass else: raise RuntimeError("generator ignored GeneratorExit") # Other exceptions are not caught Traceback (most recent call last): File "/home/evergreen/Codes/yidld.py", line 14, in <module> d = c.send('Fighting!') #d 获取了yield 12 的参数值12 StopIteration |
|