Why does the Python Iterator need an iter method that just returns self?

I understand that the standard says that it is, but I'm trying to find the root cause of this.

If he just always returns self, what does he need?

Do you explicitly have access to the object since you are calling iteron that object, so you need to have it?

+4
source share
4 answers

Imagine you want to write code that iterates over any fighter. Usually you just write a statement foror understanding, but instead explicitly do what you fordo under the covers to make things more obvious:

i = iter(iterable)
while True:
    try:
        val = next(i)
    except StopIteration:
        break
    else:
        do_stuff(val)

, , , , .

, , iter(iterable) , .


, iter ? , , , __len__ __getitem__, __iter__, , , a __next__, __iter__? , , , Python . , - , ( ) , , .

+7

for , for i in something: iter(something), . , (.. __iter__), for , :

items = [1, 2, 3]
# this would work
for item in items: pass
# this wouldn't
it = iter(items)
for item in it: pass

. , "- " iter , ( ?).

+1

, for , , iter , , , . , next, .

0

__iter__()designed to return an iterator over an object. What is an iterator over an object that is already an iterator? self, of course.

0
source

Source: https://habr.com/ru/post/1523629/


All Articles