- Mastering Objectoriented Python
- Steven F. Lott
- 197字
- 2021-11-12 16:25:16
The iterator abstraction
Iterators are created implicitly when we use an iterable container with a for
statement. We rarely care about the iterator itself. And the few times we do care about the iterator, we rarely want to extend or revise the class definition.
We can expose the implicit iterators that Python uses via the iter()
function. We can interact with an iterator in the following way:
>>> x = [ 1, 2, 3 ] >>> iter(x) <list_iterator object at 0x1006e3c50> >>> x_iter = iter(x) >>> next(x_iter) 1 >>> next(x_iter) 2 >>> next(x_iter) 3 >>> next(x_iter) Traceback (most recent call last): File "<stdin>", line 1, in <module> StopIteration >>> isinstance( x_iter, collections.abc.Iterator ) True
We created an iterator over a list object and then stepped through the values in that iterator using the next()
function.
The final isinstance()
expression confirmed that this iterator object is an instance of collections.abc.Iterator
.
Most of the time, we'll work with iterators that have been created by the collection classes themselves. However, when we branch out and build our own collection classes or extend a collection class, we may also need to build a unique iterator. We'll look at iterators in Chapter 6, Creating Containers and Collections.