Iterator & Generator
Iterator
The iterator objects themselves are required to support the following two methods, which together form the iterator protocol:
iterator.__iter__
()Return the iterator object itself. This is required to allow both containers and iterators to be used with the
for
andin
statements. This method corresponds to thetp_iter
slot of the type structure for Python objects in the Python/C API.
iterator.__next__
()Return the next item from the container. If there are no further items, raise the
StopIteration
exception. This method corresponds to thetp_iternext
slot of the type structure for Python objects in the Python/C API.
Generator
Generator 是一种特殊的 iterator。
Generator Expressions
Yield Expressions
yield 表达式可以拥有值。
generator.__next__()
Starts the execution of a generator function or resumes it at the last executed yield expression.
generator.send(value)
Resumes the execution and “sends” a value into the generator function. The value argument becomes the result of the current yield expression. The
send()
method returns the next value yielded by the generator, or raisesStopIteration
if the generator exits without yielding another value.
If a container object’s
__iter__()
method is implemented as a generator, it will automatically return an iterator object (technically, a generator object) supplying the__iter__()
and__next__()
methods.When
yield from <expr>
is used, the supplied expression must be an iterable. The values produced by iterating that iterable are passed directly to the caller of the current generator’s methods.
Reference
[1] https://docs.python.org/3/library/stdtypes.html#iterator-types
[2] https://docs.python.org/3/reference/expressions.html#generator-expressions
Last updated
Was this helpful?