Why does the class need __iter __ () to return an iterator?

Why should a class define __iter__()a self return in order to get a class iterator?

class MyClass:
    def __init__(self):
        self.state = 0

    def __next__(self):
        self.state += 1
        if self.state > 4:
            raise StopIteration
        return self.state

myObj = MyClass()
for i in myObj:
    print(i)

Console Log:

Traceback (most recent call last):
   for i in myObj:
TypeError: 'MyClass' object is not iterable

response qaru.site/questions/194 / ... , says

An iterator is an object with the following (Python 2) or __next__(Python 3) method.

The task of adding the following:

def __iter__(self):
   return self

should return an iterator or class object that defines the method __next__().

But is it not a task to return the MyClass object (which defines the method __next__()) already executed by the method __new__(), when MyClass is created in the line myObj = MyClass ()?

Won't class objects that define the method __next__()be iterators on their own?

__iter__? Iterator Python, , __iter__() self.

+4
2

, __iter __() , , for-loop , iter() , . __iter __() for-loops. iter(), __next __() .

:

1) __iter __(), .

2) __next __(), , , StopIteration .

3) __iter __(), self. , .

, __iter __(), self, , :

>>> s = 'hello world'
>>> it = iter(s)
>>> next(it)
'h'
>>> next(it)
'e'
>>> list(it)     # Doesn't start from the beginning
['l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']

, , :

>>> s = 'hello world'
>>> it = iter(s)
>>> list(zip(it, it))
[('h', 'e'), ('l', 'l'), ('o', ' '), ('w', 'o'), ('r', 'l')]

:

1) - __getitem __(), IndexError. str Python 2.

2) , , . , next() . , ( , ).

3) , , Python. : https://en.wikipedia.org/wiki/Iterator_pattern

+7

__new__()

, __new__ - , __iter__ .

, __next__(), ?

, , __next__, __iter__. __next__ , , . __iter__ , for .

, __next__ ( ), someones __iter__. , MyClass CustomIter, __next__:

class MyClass:
    def __iter__(self): 
        return CustomIter()

class CustomIter(object):

    def __init__(self): 
        self.state = 0

    def __next__(self): 
        self.state += 1
        if self.state > 4:
            raise StopIteration
        return self.state

__iter__, , ( ), __next__.


__iter__ :

def __iter__(self): return self

__next__ type(self) (), . __next__ self, .

, __iter__ , __next__ ( ). , __iter__.

:

class MyClass:
    def __init__(self):
        self.state = 0

    def __iter__(self): 
        for i in range(10): yield i

a __next__. iter:

g = iter(MyClass())

g, __next__:

g = iter(MyClass())

g.__next__() # 0
g.__next__() # 1
+3

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


All Articles