Looking for doh!.. simple sequence type

Greg Ewing greg at cosc.canterbury.ac.nz
Sun Apr 14 23:18:08 EDT 2002


Steffen Kirschke wrote:
> 
> or, instead of __getitem__
> 
>         def __iter__(self):
>                 self.iter = 0
>                 return self
> 
>         def next(self):
>                 if self.iter == self.len:
>                         raise StopIteration
>                 else:
>                         self.iter += 1
>                         return 42

The __iter__ method should really create and return
a new object, otherwise two for-loops iterating
over the same object will get in each other's way.
For example,

  class LstIter:

    def __init__(self, seq):
      self.seq = seq
      self.count = 0

    def next(self):
      if self.count == self.seq.len:
        raise StopIteration
      else:
        return 42

  class Lst:
    ...
    def __iter__(self):
      return LstIter(self)

-- 
Greg Ewing, Computer Science Dept, University of Canterbury,	  
Christchurch, New Zealand
To get my email address, please visit my web page:	  
http://www.cosc.canterbury.ac.nz/~greg



More information about the Python-list mailing list