More baby squeaking - iterators in a class

Scott David Daniels Scott.Daniels at Acm.Org
Thu Dec 30 15:06:31 EST 2004


Bulba! wrote:
> Hello Mr Everyone,
> 
> From:
> http://docs.python.org/tut/node11.html#SECTION0011900000000000000000
> 
> "Define a __iter__() method which returns an object with a next()
> method. If the class defines next(), then __iter__() can just return
> self:"
> 
> The thing is, I tried to define __iter__() directly without explicit 
> defining next (after all, the conclusion from this passage should
> be that it's possible).
> 
> 
> class R:
> 	def __init__(self, d):
> 		self.d=d
> 		self.i=len(d)
> 	def __iter__(self):
> 		if self.i == 0:
> 			raise StopIteration
> 		self.i -= 1
> 		return self.d[self.i]

Here's one way:  # (Make __iter__ an iterator)

Py> class R1(object):
         def __init__(self, data):
             self.data = data
             self.i = len(data)
         def __iter__(self):
             while self.i > 0:
                 self.i -= 1
                 yield self.data[self.i]

Py> s=R1('spam')
Py> list(s)
['m', 'a', 'p', 's']
Py> list(s)
[]
Py> s.i = 3
Py> list(s)
['a', 'p', 's']

Here's another way: # (Return something with __iter__ and next methods)

Py> class R2(object):
         def __init__(self, data):
             self.d = data
             self.i = len(data)
         def __iter__(self):
             return iter(self.d)
Py> s = R2('spam')
Py> list(s)
['s', 'p', 'a', 'm']
Py> list(s)
['s', 'p', 'a', 'm']

--Scott David Daniels
Scott.Daniels at Acm.Org



More information about the Python-list mailing list