yield作为python内置关键字,译为生产。在函数中可暂时认为 return 的替代品。
如果某函数包含 yield,直接调用此函数时,函数并不直接执行函数逻辑,而是返回一个generator。 通过调用 generator.next() 或 item (for循环) 触发函数执行,执行到yield时,可视为返回yield后的值。
其好处在于在需要结果时才执行获取,不必提前申请过多内存信息来存取处理结果列表。
(日常开发不太用,源码中比较常见,调用接口时需要捋清使用方法)
yield代码简单示例(斐波那契)
def fab(max): n, a, b = 0, 0, 1 while n < max: print b a, b = b, a + b n = n + 1 fab(6)
输出:
1
1
2
3
然后我们将使用 yeild 声明 b, 相当于每次调用fab时,返回b。 代码如下
def fab_yield(max): n, a, b = 0, 0, 1 while n < max: yield b a, b = b, a + b n = n + 1
# 函数返回生成器,并不会触发逻辑执行 generator = fab_yield(4) # 为了更容易理解,调用4个.next来获取数据,日常可以直接使用for i in fab_yield
print(y.next()) print(y.next()) print(y.next()) print(y.next())
# 多余的next调用会StopIteration异常
输出:
1
1
2
3
上面提到使用 for i in fab_yield()同样可以取出数据,那顺带一下python中for循环的原理
python for 原理
python中可迭代的对象很多。列表、元组、字典等都可以,这些对象必须都有 __iter__ 和 next 方法。
其中__iter__返回一个Iterator(类似生成器),使用for遍历对象时相当于调用__iter__获取一个Iterator,然后调用 next 遍历数据。
for 流程验证用例:
class Te: def __init__(self): self.a = 0 def __iter__(self): print("call iter") return self def next(self): print("call next") if self.a >= 3: raise StopIteration() self.a += 1 return self.a t=Te() for i in t: print(i) 输出: call iter call next 1 call next 2 call next 3 call next