views:

61

answers:

2

For dictionary, I can use iter() for iterating over keys of the dictionary.

y = {"x":10, "y":20}
for val in iter(y):
    print val

When I have the iterator as follows,

class Counter:
    def __init__(self, low, high):
        self.current = low
        self.high = high

    def __iter__(self):
        return self

    def next(self):
        if self.current > self.high:
            raise StopIteration
        else:
            self.current += 1
            return self.current - 1

Why can't I use it this way

x = Counter(3,8)
for i in x:
    print x

nor

x = Counter(3,8)
for i in iter(x):
    print x

but this way?

for c in Counter(3, 8):
    print c

What's the usage of iter() function?

ADDED

I guess this can be one of the ways of how iter() is used.

class Counter:
    def __init__(self, low, high):
        self.current = low
        self.high = high

    def __iter__(self):
        return self

    def next(self):
        if self.current > self.high:
            raise StopIteration
        else:
            self.current += 1
            return self.current - 1

class Hello:
    def __iter__(self):
        return Counter(10,20)

x = iter(Hello())
for i in x:
    print i
+4  A: 

All of these work fine, except for a typo--you probably mean:

x = Counter(3,8)
for i in x:
    print i

rather than

x = Counter(3,8)
for i in x:
    print x
Glenn Maynard
@Glenn : When iter(x) and x gives the same result, what's for the iter()? Thanks for finding the typo.
prosseek
`iter` converts an object to an iterator (that is, it returns the iterator for an object). When the object is *already* an iterator, this does nothing and `__iter__` simply returns itself. `for i in x` is actually calling `iter` *for* you; since that's unnecessary (it's already an iterator), the iterator's `__iter__` call returns itself.
Glenn Maynard
+4  A: 

I think your actual problem is that you print x when you mean to print i

iter() is used to obtain an iterator over a given object. If you have an __iter__ method that defines what iter will actually do. In your case you can only iterate over the counter once. If you defined __iter__ to return a new object it would make it so that you could iterate as many times as you wanted. In your case, Counter is already an iterator which is why it makes sense to return itself.

Winston Ewert