Method returning an Iterable Object

Andreas Waldenburger geekmail at usenot.de
Mon Jan 26 12:01:52 EST 2009


On Mon, 26 Jan 2009 22:01:21 +0530 Anjanesh Lekshminarayanan
<mail at 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 next() and create another method named __iter__()
that just returns self. TwoTimes is now an iterator.

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)
    for number in in infinitely_doubling_numbers:
        print number

to the same effect as the iterator version above.

python.org seems uncooperative at the moment, but look up iterators or
the iterator protocol and generators if it works for you.


> t = twoTimes(5)
> while (n in t.getNext()): # while (n in t):
>     print (n)
> 
You are aware that this is an infinite loop, as is my example above BTW?
(Probably just an example, but I ask just in case.)

Also, could it be that you mean "for n in t"?

regards
/W

-- 
My real email address is constructed by swapping the domain with the
recipient (local part).



More information about the Python-list mailing list