为什么可迭代对象不是迭代器? [英] Why is an iterable object not an iterator?
问题描述
这是我的代码:
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__
方法.
I have no idea why the linehistory
object is not an iterator since it has already included __iter__
method in the
class.
推荐答案
迭代的概念已得到充分证明 Python文档中的.
The concept of iteration is well documented in the Python documentation.
简而言之,可迭代"是我要迭代的对象,也称为容器.这可以是列表,字符串,元组或其他任何包含或可以产生多个项目的内容.它具有__iter__()
返回迭代器.
In short, "iterable" is the object I want to iterate over, also called the container. This can be a list, a string, a tuple or anything else which consists of or can produce several items. It has __iter__()
which returns an iterator.
迭代器"是用于一次迭代的对象.可以将其视为一种光标".它具有next()
(在Python 2中)或__next__()
(在Python 3中),被重复调用直到引发StopIteration
异常.由于任何迭代器也都是可迭代的(作为其自己的迭代器),因此它还具有返回其自身的__iter__()
.
An "iterator" is the object which is used for one iteration. It can be seen as a kind of "cursor". It has next()
(in Python 2) or __next__()
(in Python 3) which is called repeatedly until it raises a StopIteration
exception. As any iterator is iterable as well (being its own iterator), it also has __iter__()
which returns itself.
您可以使用iter(obj)
获得任何可迭代的迭代器.
You can get an iterator for any iterable with iter(obj)
.
在您的示例中,linehistory
(应写为LineHistory
)是可迭代的,因为它具有.__iter__()
.以此创建的生成器对象是一个迭代器(就像每个生成器对象一样).
In your example, linehistory
(which should be written LineHistory
) is iterable as it has an .__iter__()
. The generator object created with this is an iterator (as every generator object).
这篇关于为什么可迭代对象不是迭代器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!