python - Why does a class need __iter__() to return an iterator? -
why class need define __iter__() returning self, iterator of 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() in myobj: print(i) console log: traceback (most recent call last): in myobj: typeerror: 'myclass' object not iterable the answer https://stackoverflow.com/a/9884259/4515198 , says an iterator object next (python 2) or __next__ (python 3) method. the task of adding following: def __iter__(self): return self is return iterator , or object of class, defines __next__() method. but, isn't task of returning object of myclass (which defines __next__() method) done __new__() method, when myclass instantiated in line myobj = myclass() ? won't objects of class defining __next__() method, iterators themselves? i have studied questions what use of returnin...