擅长:python、mysql、java
<p>每次生成器<code>yield</code>s时,生成器的堆栈帧都保存在生成器对象中,因此<a href="https://github.com/python/cpython/blob/3.6/Objects/genobject.c#L184" rel="nofollow noreferrer">it can be restored when execution resumes</a>(当请求下一个值时)。在</p>
<p>您可以看到<a href="https://github.com/python/cpython/blob/3.6/Include/genobject.h#L15" rel="nofollow noreferrer">the structure definition on CPython here</a>。在</p>
<p>如果您想了解更多,生成器有点内省,因此您可以查看,例如,局部变量的进展,它当前的行号,等等:</p>
<pre><code>def myrange(n):
for i in range(n):
yield i
mr = myrange(10)
# Before any values consumed:
print(mr.gi_frame.f_locals) # Outputs {'n': 10}
print(mr.gi_frame.f_lineno) # Outputs 1
next(mr) # Advance one
print(mr.gi_frame.f_locals) # Outputs {'n': 10, 'i': 0}
print(mr.gi_frame.f_lineno) # Outputs 3
list(mr) # Consumes generator
print(mr.gi_frame) # Outputs None; the frame is discarded when the generator finishes
</code></pre>