PyGenObject
本文参考的是 3.8.0a0 版本的代码,详见 cpython 源码分析 基本篇
以后都在 github 更新,请参考 图解 python generator
用过 python 的同学都知道 python 内置了一个类型叫做 generator, 翻译过来是迭代器/生成器
generator 也是一种设计模式,在其他语言里面,只要能记录下函数/某个算法运行的状态,就可以通过不同的技巧来实现 generator
比如生成斐波那契数列:
class Fib(object):
def __init__(self):
self.curr_val = 0
self.next_val = 1
def next(self):
next_val = self.next_val
self.next_val = self.curr_val + self.next_val
self.curr_val = next_val
return self.curr_val
def fib2():
curr_val = 0
next_val = 1
while True:
temp_next_val = next_