Обложка канала

Библиотека Python разработчика

20835 @BookPython

Библиотека Python разработчика. Книги по программированию на Python.

Библиотека Python разработчика

4 года назад
Открыть в
Two things in Python can be confused: iterables and iterators. Iterables are objects that can be iterated, i. e. there is a way to extract some values from that object, one by one, probably infinitely. Iterables are usually some collections like arrays, sets, lists, etc. There are two ways an object can become a proper iterable. The first one is to have __getitem__ method: In : class Iterable: ...: def __getitem__(self, i): ...: if i > 10: ...: raise IndexError ...: return i ...: In : list(Iterable()) Out: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] The second way is to define __iter__ method that returns an iterator. An iterator is an object with a __next__ method that returns next value from the original iterable once called: In : class Iterator: ...: def __init__(self): ...: self._i = 0 ...: ...: def __next__(self): ...: i = self._i ...: if i > 10: ...: raise StopIteration ...: self._i += 1 ...: return i ...: ...: class Iterable: ...: def __iter__(self): ...: return Iterator() ...: ...: In : list(Iterable()) Out: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] Usually, an iterator also has an __iter__ method that just returns self: it allows iterator to be iterated too, that means that most of the iterators are also iterables.