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)
--
Anjanesh Lekshmnarayanan
--
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
On Mon, 26 Jan 2009 22:01:21 +0530 Anjanesh Lekshminarayanan
m...@anjanesh.net 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
Rename getNext() to
You can also replace the whole class with a function thusly:
def two_times(n):
for k in itertools.count(1):
yield n * (2**k)
This function is then called a generator (because it generates an
iterator). You can now say
infinitely_doubling_numbers = two_times(2)
On Tue, 27 Jan 2009 00:05:53 +0530 Anjanesh Lekshminarayanan
m...@anjanesh.net wrote:
You can also replace the whole class with a function thusly:
def two_times(n):
for k in itertools.count(1):
yield n * (2**k)
This function is then called a generator (because
But how come a raise StopIteration in the next() method doesnt need to
be caught ? It works without breaking.
class twoTimes:
max = 10**10
def __init__(self, n):
self.__n = n
def next(self):
if self.__n self.max:
raise StopIteration
self.__n *= 2
On Tue, Jan 27, 2009 at 1:16 PM, Anjanesh Lekshminarayanan
m...@anjanesh.net wrote:
But how come a raise StopIteration in the next() method doesnt need to
be caught ? It works without breaking.
Because this exception is specially dealt
with when iterating over an iterator. The
raise
Anjanesh Lekshminarayanan wrote:
But how come a raise StopIteration in the next() method doesnt need to
be caught ? It works without breaking.
The for-loop looks for and catches StopIteration. It is an essential
part of what defines a finite iterator.
(Note, in 3.0, next is renamed __next__