(推荐操作系统:windows7系统、Python 3.9.1、DELL G3电脑。)
1、如果你想让你的生成器暴露外部状态给用户, 别忘了你可以简单的将它实现为一个类,然后把生成器函数放到 __iter__() 方法中过去。比如:
fromcollectionsimportdeque classlinehistory: def__init__(self,lines,histlen=3): self.lines=lines self.history=deque(maxlen=histlen) def__iter__(self): forlineno,lineinenumerate(self.lines,1): self.history.append((lineno,line)) yieldline defclear(self): self.history.clear()
2、为了使用这个类,你可以将它当做是一个普通的生成器函数。然而,由于可以创建一个实例对象,于是你可以访问内部属性值,比如 history 属性或者是 clear() 方法。代码示例如下:
with open('somefile.txt') as f:
lines = linehistory(f)
for line in lines:
if 'python' in line:
for lineno, hline in lines.history:
print('{}:{}'.format(lineno, hline), end='')
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。
评论(0)