Dav*_*542 6 python generator python-3.x
我创建了以下生成器函数:
>>> def file_readlines(filepath):
... f = open(filepath, 'r')
... for line in f:
... yield line
...
>>> gen=file_readlines(filepath)
>>> next(gen)
Run Code Online (Sandbox Code Playgroud)
当我检查生成器的方法时,它显示以下内容:
Run Code Online (Sandbox Code Playgroud)...'close', 'gi_code', 'gi_frame', 'gi_running', 'gi_yieldfrom', 'send', 'throw'`
throw、send、 和close记录在Python Expressions中,我想象code和frame类似于堆栈跟踪对象,但是gi_running和是什么gi_yieldfrom?那些是如何使用的?
gi_running告诉您解释器当前是否正在执行生成器框架中的指令 ( gi_frame)
gi_yieldfrom是生成器产生的迭代器。它是在 3.5 中引入的,您可以在这里阅读增强票: https: //bugs.python.org/issue24450
def yielder(gen):
yield from gen
x = range(5)
g = yielder(x)
print(g.gi_yieldfrom) # None
next(g) # delegate to the other iterator
print(g.gi_yieldfrom) # <range_iterator object at 0x0000026A0D72C830>
list(g) # exhaust iterator
print(g.gi_yieldfrom) # None
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1238 次 |
| 最近记录: |