Python iterator and Generator
You can also implement an iterator by yourself. As mentioned above, you only need to return an object in the _ iter _ method of the class. This object has a next () method, this method can throw a StopIteration exception when appropriate. However, there is not much time to implement the iterator by yourself. It is easier to use the generator even if needed. #! /Usr/bin/env python # coding = UTF-8 class test: def _ init _ (self, input_list): self. list = input_list self. I = 0 def _ iter _ (self): return self def next (self): if self. I = len (self. list): self. I = 0 raise StopIteration self. I + = 1 return self. list [self. i-1] an obvious advantage of using an iterator is that reading only one piece of data from an object at a time does not cause excessive memory overhead. For example:/* load the file to the memory once and print it row by row. When the file size is large, the memory overhead of this method is very high */for line in open ("test.txt "). readlines (): print line/* This is the simplest and fastest way of writing. He does not explicitly read files, instead, the iterator is used to read the next line */for line in open ("test.txt"): # use file iterators print line generator. The compilation method is similar to the function definition, only change the return value to yield. The generator can have multiple yield instances. When the generator encounters a yield, it will pause running the generator and return the value following yield. When the generator is called again, it will continue running from the paused place until the next yield. The generator itself forms an iterator that uses a value returned by yield for each iteration. Note that the return statement is not required in the generator, and the return value is not required. A default return Statement generator expression (I for I in range (5) already exists in the generator )) // return iterator <generator object <genexpr> at 0x7ff3e8f0d960> list parsing, returns list [I for I in range (5)] // returns list [0, 1, 2, 3, 4]