Reuseable iterators - which is better?

zefciu zefirek at Speacock.Pau.Apoznan.Mpl
Fri Jun 23 08:06:43 EDT 2006


In the tutorial there is an example iterator class that revesrses the
string given to the constructor.  The problem is that this class works
only once, unlike built-in types like string.  How to modify it that it
could work several times?  I have tried two approaches.  They both work,
but which of them is stylistically better?

class Reverse: #original one
    "Iterator for looping over a sequence backwards"
    def __init__(self, data):
        self.data = data
        self.index = len(data)
    def __iter__(self):
        return self
    def next(self):
        if self.index == 0:
            raise StopIteration
        self.index = self.index - 1
        return self.data[self.index]

class Reverse: #1st approach
    "Reuseable Iterator for looping over a sequence backwards"
    def __init__(self, data):
        self.data = data
        self.index = len(data)
    def __iter__(self):
        return self
    def next(self):
        if self.index == 0:
            	self.index = len(self.data) #Reset when previous 								#
iterator goes out
		raise StopIteration
        self.index = self.index - 1
        return self.data[self.index]

class Reverse: #2nd approach
    "Reuseable Iterator for looping over a sequence backwards"
    def __init__(self, data):
        self.data = data
    def __iter__(self):
	self.index = len(self.data) #Reset as a part of iterator 							# creation
        return self
    def next(self):
        if self.index == 0:
            raise StopIteration
        self.index = self.index - 1
        return self.data[self.index]



More information about the Python-list mailing list