python iterables and iterators

Often mistakes are made when building iterables and iterators, because the two are confused. You know, iterable objects have a __iter__ method, which instantiates a new iterator each time; and the iterator implements the __next__ method, which returns a single element, and the __iter__ method, which returns the iterator itself.

So iterators can iterate, but iterable objects are not iterators.

For example, the string "hello world" is an iterable object. Calling the iter method on the string (it = iter("hello world")) will return an iterator it, which has __iter__ and __next__ methods. The __next__ method puts back the next element, and the __iter__ method returns the iterator itself.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325222818&siteId=291194637