开发者

Iterator (iter()) function in Python. [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
开发者_开发技巧

This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.

Closed 10 days ago.

The community reviewed whether to reopen this question 10 days ago and left it closed:

Original close reason(s) were not resolved

Improve this question

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


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜