yield 浅析

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/jancywen/article/details/81060931

yield 的作用就是把一个函数变成一个 generator,并且获得了迭代能力

def fab(max):
    n, a, b = 0, 0, 1
    while n < max:
        yield b
        a, b = b, a + b
        n = n + 1

for n in fab(5):
    print(n)

OUT: 
1
1
2
3
5

这里的迭代能力不是函数获得了迭代能力,而是函数的实例获得了迭代能力,fab 是一个 generator function,而 fab(5) 是调用 fab 返回的一个 generator

import types

print(isinstance(fab, types.GeneratorType))
print(isinstance(fab(5), types.GeneratorType))

OUT: False
OUT: True

fab不具有迭代能力,fab(5)具有迭代能力

from collections import Iterable

print(isinstance(fab, Iterable))
print(isinstance(fab(5), Iterable))

OUT:
False
True

在一个 generator function 函数中,执行至函数完毕,或者直接return出函数,会抛出 StopIteration 终止迭代。

f = fab(3)
for i in range(10):

    try:
        num = f.__next__()
    except StopIteration:
        print('StopIteration')
        break
    else:
        print(num)

OUT:
1
1
2
StopIteration

另外:每次调用 fab 函数都会生成一个新的 generator 实例,各实例互不影响。

了解更多:廖雪峰:Python yield 使用浅析


猜你喜欢

转载自blog.csdn.net/jancywen/article/details/81060931