Why does a class need to define __iter__() returning self, to get an iterator of the class?
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
the answer https://stackoverflow.com/a/9884259/4515198, says
An iterator is an object with a next (Python 2) or
__next__(Python 3) method.
The task of adding the following:
def __iter__(self):
return self
is to return an iterator, or an object of the class, which defines the __next__() method.
But, isn't the task of returning an object of MyClass (which defines the __next__() method) already done by the __new__() method, when MyClass is instantiated in the line myObj = MyClass() ?
Won't the objects of a class defining __next__() method, be iterators by themselves?
I have studied the questions What is the use of returning self in the __iter__ method? and Build a Basic Python Iterator, but I am still unable to understand the reason for having an __iter__() method returning self.