这是我的代码:
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__
方法。
原文由 pipi 发布,翻译遵循 CC BY-SA 4.0 许可协议
迭代的概念 在 Python 文档中有详细记录。
简而言之,“可迭代”是提供我想要迭代的项目的对象。要么它已经包含了这些项目,那么它也被称为容器。这可以是一个列表、一个字符串、一个元组或任何其他由零到多个项目组成的东西。但它也可以是生成项目的对象,例如
itertools
中包含的许多类之一。它有__iter__()
返回一个迭代器。“迭代器”是用于一次迭代的对象。它可以看作是一种“游标”。它有
next()
(在 Python 2 中)或__next__()
(在 Python 3 中)被重复调用,直到它引发StopIteration
异常由于任何迭代器也是可迭代的(作为它自己的迭代器),它也有__iter__()
返回自身。您可以使用
iter(obj)
获得任何可迭代对象的迭代器。在你的例子中,
linehistory
(应该写成LineHistory
)是可迭代的,因为它有一个.__iter__()
。用它创建的生成器对象是一个迭代器(就像每个生成器对象一样)。