gpt4 book ai didi

python - 为什么可迭代对象不是迭代器?

转载 作者:太空狗 更新时间:2023-10-29 16:54:45 26 4
gpt4 key购买 nike

这是我的代码:

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 对象不是迭代器,因为它已经在 类中包含了 __iter__ 方法。

最佳答案

迭代的概念有据可查in the Python documentation .

简而言之,“可迭代”是提供我要迭代的项目的对象。要么它已经包含了这些项目,那么它也被称为容器。这可以是一个列表、一个字符串、一个元组或任何其他由零到多个项目组成的东西。但它也可以是一个生成项目的对象,例如 itertools 中包含的许多类之一。它有 __iter__() 返回一个迭代器。

“迭代器”是用于一次迭代的对象。它可以看作是一种“游标”。它具有 next()(在 Python 2 中)或 __next__()(在 Python 3 中),它会被重复调用,直到引发 StopIteration 异常.由于任何迭代器也是可迭代的(作为它自己的迭代器),它也有返回自身的 __iter__()

您可以使用 iter(obj) 为任何可迭代对象获取迭代器。

在您的示例中,linehistory(应该写成LineHistory)是可迭代的,因为它有一个.__iter__()。用它创建的生成器对象是一个迭代器(与每个生成器对象一样)。

关于python - 为什么可迭代对象不是迭代器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33956034/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com