Python yield 的使用方法

 
 

带有 yield 的函数在 Python 中被称之为 generator(生成器)

使用 yield 可以大大简化代码,yield 返回的是一个generator对象,带有 yield 的函数不再是一个普通函数

>>> def fab(max):
...     n,a,b = 0,0,1
...     while n<max:
...             yield b
...             a, b = b, a+b
...             n = n+1
... 
>>> fab(5) //yield 的作用就是把一个函数变成一个 generator,带有 yield 的函数不再是一个普通函数
<generator object fab at 0x10d47b5a0>
>>> for n in fab(5):
...     print n
... 
1
1
2
3
5
>>> 

Python 解释器会将其视为一个 generator,调用 fab(5) 不会执行 fab 函数,而是返回一个 iterable 对象!在 for 循环执行时,每次循环都会执行 fab 函数内部的代码,执行到 yield b 时,fab 函数就返回一个迭代值,下次迭代时,代码从 yield b 的下一条语句继续执行,而函数的本地变量看起来和上次中断执行前是完全一样的,于是函数继续执行,直到再次遇到 yield。

>>> f = fab(5)
>>> f.next()
1
>>> f.next()
1
>>> f.next()
2
>>> f.next()
3
>>> f.next()
5
>>> f.next()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration
>>> 

当函数执行结束,generator 自动抛出StopInteration异常,表示迭代完成。在for 循环里,无需处理StopIteration异常,循环结束。



猜你喜欢

转载自blog.csdn.net/w_han__/article/details/79626309
今日推荐