Here is my code:
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)
Error:
Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'linehistory' object is not an iterator
I have no idea why the linehistory
object is not an iterator since it has already included __iter__
method in the
class.
Summary. An iterable is an object that implements the __iter__ method which returns an iterator. An iterator is an object that implements the __iter__ method which returns itself and the __next__ method which returns the next element. Iterators are also iterables.
An Iterable is basically an object that any user can iterate over. An Iterator is also an object that helps a user in iterating over another object (that is iterable). We can generate an iterator when we pass the object to the iter() method. We use the __next__() method for iterating.
A list object is not an iterator because it does not have a __next__() method.
Iterator is an interface, which has implementation for iterate over elements. Iterable is an interface which provides Iterator.
The concept of iteration is well documented in the Python documentation.
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.
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.
You can get an iterator for any iterable with iter(obj)
.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With