Iterators (iterator)
An object that represents the data stream. Repeated calls to the iterator's__next__()
Method (or pass the built-in function to it (built-in functions)next()
) to return a successor in the stream. When no data is available, it produces aStopInteration
Abnormal. At this point, the iterator object is exhausted and then called__next__()
Method will only be generated againStopInteration
Abnormal. Iterators require a__iter__()
method, which is used to return the iterator object itself, so each iterator is also iterative, which can be used for most scenarios where an iteration (object) is accepted. One notable exception is the code that attempts to pass multiple iterations. A container object (for example,list
), passing it every timeiter()
function or usefor
Loop, a new iterator is generated. This attempt in an iterator, passing through the previous iteration, also produces an exhausted iterator object, which makes it look like an empty container.
Iterator type (Iterator Types)
Python supports the concept of iterations on top of a container. This is implemented by two distinct methods, which are used to enable user-defined classes (user-defined classes) to support iterations. 序列(Sequences)
, the iteration method is always supported, which is described in detail below.
In a container object, you need to define a method to provide iterative support:
Container.__iter__()
Returns an Iterator object. This object requires the ability to support the iteration protocol described below. If a container supports different types of iterations, additional methods can be provided to request the specified iterator for these different types. (An object supports multiple forms of iteration, just as a tree structure supports breadth-first and depth-first traversal.) This method corresponds to the tp_iter
slot (slot) of the type structure of the Python object in the Python/c API.
The iterator object itself requires support for the following two methods that make up the iterator protocol:
Iterator.__iter__()
Returns the Iterator object itself. This is required so that it can be used in containers and iteratorsfor
statements, andin
Statement. This method corresponds to the type structure of the Python object in the Python/c API.tp_iter
Slot.
iterator.__next__ ()
Returns the next item from the container. If not, trigger stopiteration
exception. The method corresponds to the type structure of the Python object in the PYTHON/C API tp_iternext
slot.
Python defines a variety of iterator objects to support iterations over common and specific sequence types, dictionaries, and other specific forms. It is not important that these specific types are outside of the iterator protocol implementation.
Once a method of an iterator is __next__()
thrown StopIteration
, this must also be done in the subsequence call. Implementations that do not follow this attribute are considered to be invalid.
Python iterator (iterator)