next up previous contents
Next: About this document ... Up: Writing Modules Previous: Adding Methods to the   Contents


Iterators

Now suppose that we'd like to be able to iterate over the keys of our ODict object using a for loop, with the keys presented in the order in which they were added. To acheive this goal, we need to define an __iter__ method which simply returns itself, and a next method to return the keys in the order we desire. When you implement an iterator, it's your responsibility to raise a StopIteration exception when the items of your object are exhausted. Furthermore, you'll usually need to define a new attribute in your object to help you keep track of the most recently returned element. In this example, you'd need to set the self.count variable to 0 in the __iter__ method. The other additions which are required are shown below:
        def iter(self):
           self.count = 0
           return(self)

        def next:
           if self.count >= len(self._okeys):
               raise StopIteration
            
           rval = self._okeys[self.count]
           self.count = self.count + 1
           return(rval)



Phil Spector 2003-11-12