2018年2月25日 星期日

[ Python 常見問題 ] Build a Basic Python Iterator

Source From Here 
Question 
How would one create an iterative function (or iterator object) in python? 

How-To 
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: 
  1. class Counter:  
  2.     def __init__(self, low, high):  
  3.         self.current = low  
  4.         self.high = high  
  5.   
  6.     def __iter__(self):  
  7.         return self  
  8.   
  9.     def next(self): # Python 3: def __next__(self)  
  10.         if self.current > self.high:  
  11.             raise StopIteration  
  12.         else:  
  13.             self.current += 1  
  14.             return self.current - 1  
  15.   
  16.   
  17. for c in Counter(38):  
  18.     print c  
This will print: 
3
4
5
6
7
8

This is easier to write using a generator, as covered in a previous answer: 
  1. def counter(low, high):  
  2.     current = low  
  3.     while current <= high:  
  4.         yield current  
  5.         current += 1  
  6.   
  7. for c in counter(38):  
  8.     print c  
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. 

Supplement 
FAQ - What makes something iterable in python 
FAQ - In Python, how do I determine if an object is iterable? 

沒有留言:

張貼留言

[Linux 常見問題] What's the best way to send a signal to all members of a process group?

Source From  Here   Question   I want to  kill a whole process tree.  What is the best way to do this using any common scripting languages? ...