12.07.2015 Views

Is Python a

Is Python a

Is Python a

SHOW MORE
SHOW LESS
  • No tags were found...

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

class SkipIterator:def _ _init_ _(self, wrapped):self.wrapped = wrappedself.offset = 0def next(self):if self.offset >= len(self.wrapped):raise StopIterationelse:item = self.wrapped[self.offset]self.offset += 2return itemclass SkipObject:def _ _init_ _(self, wrapped):self.wrapped = wrappeddef _ _iter_ _(self):return SkipIterator(self.wrapped)# Iterator state information# Terminate iterations# else return and skip# Save item to be used# New iterator each timeif _ _name_ _ == '_ _main_ _':alpha = 'abcdef'skipper = SkipObject(alpha)# Make container objectI = iter(skipper)# Make an iterator on itprint I.next(), I.next( ), I.next( ) # Visit offsets 0, 2, 4for x in skipper:for y in skipper:print x + y,# for calls _ _iter_ _ automatically# Nested fors call _ _iter_ _ again each time# Each iterator has its own state, offsetWhen run, this example works like the nested loops with built-in strings—eachactive loop has its own position in the string because each obtains an independentiterator object that records its own state information:% python skipper.pya c eaa ac ae ca cc ce ea ec eeBy contrast, our earlier Squares example supports just one active iteration, unless wecall Squares again in nested loops to obtain new objects. Here, there is just oneSkipObject, with multiple iterator objects created from it.As before, we could achieve similar results with built-in tools—for example, slicingwith a third bound to skip items:>>> S = 'abcdef'>>> for x in S[::2]:... for y in S[::2]: # New objects on each iteration... print x + y,...aa ac ae ca cc ce ea ec eeThis isn’t quite the same, though, for two reasons. First, each slice expression herewill physically store the result list all at once in memory; iterators, on the other hand,Operator Overloading | 497

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!