Method returning an Iterable Object

Steve Holden steve at holdenweb.com
Mon Jan 26 17:44:01 CET 2009


Anjanesh Lekshminarayanan wrote:
> Is there a way to return an iterable object ?
> 
> class twoTimes:
>     def __init__(self, n):
>         self.__n = n
> 
>     def getNext():
>         self.__n *= 2
>         return self.__n
> 
> 
> t = twoTimes(5)
> while (n in t.getNext()): # while (n in t):
>     print (n)
> 
Sure:

class EveryOther:
	def __init__(self, seq):
		self.seq = seq self.idx = 0
	def next(self):
		self.idx += 1
		if self.idx >= len(self.seq):
			raise StopIteration
		value = self.seq[self.idx]
		self.idx += 1
		return value
	def __iter__(self):
		return self


print [x for x in EveryOther(range(10))
[1, 3, 5, 7, 9]

regards
 Steve
-- 
Steve Holden        +1 571 484 6266   +1 800 494 3119
Holden Web LLC              http://www.holdenweb.com/




More information about the Python-list mailing list