【发布时间】:2015-11-27 11:06:59
【问题描述】:
这是我的代码:
from collections import deque
class linehistory:
def __init__(self, lines, histlen=3):
self.lines = lines
self.history = deque(maxlen=histlen)
def __iter__(self):
for lineno, line in enumerate(self.lines,1):
self.history.append((lineno, line))
yield line
def clear(self):
self.history.clear()
f = open('somefile.txt')
lines = linehistory(f)
next(lines)
错误:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'linehistory' object is not an iterator
我不知道为什么 linehistory 对象不是迭代器,因为它已经在 the 类中包含了 __iter__ 方法。
【问题讨论】:
-
您还需要定义一个
next()方法(或__next__()用于Python 3)。 -
__next__方法缺失:pymbook.readthedocs.org/en/latest/igd.html#iterators