Method returning an Iterable Object
Terry Reedy
tjreedy at udel.edu
Mon Jan 26 22:51:13 EST 2009
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__ in conformance with all other
special methods. In 2.6, the rename is optional, I believe.)
> class twoTimes:
> max = 10**10
>
> def __init__(self, n):
> self.__n = n
There is no reason to mangle the attribute name.
Max should be a parameter, and self.max = max added to the init.
>
> def next(self):
> if self.__n > self.max:
> raise StopIteration
> self.__n *= 2
> return self.__n
Are you sure you do not want to return once the initial value of n
passed to init?
>
> def __iter__(self):
> return self
Once you understand the above, you can rewrite it as a generator function:
def two_times(num, stop):
while num < stop:
yield num
num *=2
The two last lines can be switches if desired.
> t = twoTimes(5)
> c = 0
>
> print (t.next())
> print (t.next())
>
> for n in t:
> print n
>>> print(list(two_times(5,687)))
[5, 10, 20, 40, 80, 160, 320, 640]
Terry Jan Reedy
More information about the Python-list
mailing list