Today I am going to explain How would one create an iterative function (or iterator object) in python?
Iterator objects in python conform to the iterator protocol, which basically means they provide two methods: __iter__() and next(). The __iter__ returns the iterator object and is implicitly called at the start of loops. The next() method returns the next value and is implicitly called at each loop increment. next() raises a StopIteration exception when there are no more value to return, which is implicitly captured by looping constructs to stop iterating.
Here's a simple example of a counter:
The printed output will be the same. Under the hood, the generator object supports the iterator protocol and does something roughly similar to the class Counter. David Mertz's article, Iterators and Simple Generators, is a pretty good introduction.
Written by Vivek Soundrapandi
Published Date: {{ article.pub_date }}
View all posts by: Vivek Soundrapandi