taxik
Спасибо, а вы можете дать ссылку где это указано(можно и на англ.)?
https://docs.python.org/3/glossary.html#term-iterableWhen using iterables, it is usually not necessary to call iter() or deal with iterator objects yourself. The for statement does that automatically for you, creating a temporary unnamed variable to hold the iterator for the duration of the loop.
Можно проверить, как предлагал
terabayt :
>>> class A:
... def __iter__(self):
... print('In iter')
... self.it = iter('abc')
... return self
... def __next__(self):
... print('In next')
... return next(self.it)
...
>>> a = A()
>>> for i in a:
... print(i)
...
In iter
In next
a
In next
b
In next
c
In next
>>>
Нужно различать итератор и итерэбл:
>>> class A:
... pass
...
>>> a = A()
>>> iter(a)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'A' object is not iterable
>>>
Создание итератора из итерэбл с протоколом последовательности:
>>> class A:
... def __getitem__(self, v):
... return 'abc'[v]
...
>>> a = A()
>>> it = iter(a)
>>> it
<iterator object at 0xb7381e4c>
>>> next(it)
'a'
>>> next(it)
'b'
>>> next(it)
'c'
>>> next(it)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
>>> next(it)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
>>>