Iterable Object, Iterator, Generator, Generator Iterator

1.Definitions

Iterable Object:

Iterables include all sequence types (such as list, str, and tuple, which has __getitem__() method) and some non-sequence types like dict(has __getitem__() method), file objects(has __iter__() method), and objects of any classes you define with an __iter__() or __getitem__() method.

Iterator:

All objects that support __iter__() and __next__() magic methods.

Generator:

A normal function that contains yield expressions.

Generator Iterator:

An object created by a generator function.

2.Relations

When we use iter(iterable object), it seems that we provide iterator objects with  __next__()  magic method,and when we define a generator, we can get a generator iterator supplying the __iter__()  and __next__() methods.

3.Details on iterator

An object representing a stream of data. Repeated calls to the iterator’s __next__() method (or passing it to the built-in function next()) return successive items in the stream. When no more data are available aStopIteration exception is raised instead.

By using a iterator, we can obtain a value when needed rather than get all values at a time, which means that we can save lots of memory. However, this also means that we can only access each value for just one time, algorithms that perform this way are generally called "single pass" or "on-line" .

4.for ... in ...

#object is iterable
#The python loop
for i in object:
    do(i)

#Is equivalent to
object_iterator = iter(object)
while True:
    try:
        i = object_iterator.next()
        do(i)
    except StopIteration:
        break

5.Doc about iter()

iter(object[, sentinel])
Return an iterator object. The first argument is interpreted very differently depending on the presence of the second argument. Without a second argument, object must be a collection object which supports the iteration protocol (the __iter__() method), or it must support the sequence protocol (the __getitem__() method with integer arguments starting at 0). If it does not support either of those protocols, TypeError is raised. If the second argument, sentinel, is given, then object must be a callable object. The iterator created in this case will call object with no arguments for each call to its __next__() method; if the value returned is equal to sentinel, StopIteration will be raised, otherwise the value will be returned.

See also Iterator Types.

One useful application of the second form of iter() is to read lines of a file until a certain line is reached. The following example reads a file until the readline() method returns an empty string:
with open('mydata.txt') as fp:
    for line in iter(fp.readline, ''):
        process_line(line)
原文地址:https://www.cnblogs.com/bukekangli/p/5152451.html