Python中的迭代器(iter())函数.

pro*_*eek 17 python iterator

对于字典,我可以iter()用来迭代字典的键.

y = {"x":10, "y":20}
for val in iter(y):
    print val
Run Code Online (Sandbox Code Playgroud)

当我有迭代器如下,

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
Run Code Online (Sandbox Code Playgroud)

为什么我不能这样使用它

x = Counter(3,8)
for i in x:
    print x
Run Code Online (Sandbox Code Playgroud)

也不

x = Counter(3,8)
for i in iter(x):
    print x
Run Code Online (Sandbox Code Playgroud)

但这样呢?

for c in Counter(3, 8):
    print c
Run Code Online (Sandbox Code Playgroud)

功能的用途是iter()什么?

添加

我想这可能是如何iter()使用的方式之一.

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
Run Code Online (Sandbox Code Playgroud)

Gle*_*ard 16

所有这些工作都很好,除了拼写错误 - 你可能意味着:

x = Counter(3,8)
for i in x:
    print i
Run Code Online (Sandbox Code Playgroud)

而不是

x = Counter(3,8)
for i in x:
    print x
Run Code Online (Sandbox Code Playgroud)

  • `iter`将一个对象转换为一个迭代器(也就是说,它返回一个对象的迭代器).当对象*已经是*迭代器时,它什么都不做,而`__iter__`只是返回它自己.`for in in x`实际上是为了'你'而叫'iter`*因为那是不必要的(它已经是迭代器),迭代器的`__iter__`调用会返回自己. (6认同)

Win*_*ert 8

我认为你的实际问题是print x你的意思print i

iter()用于获取给定对象上的迭代器.如果你有一个__iter__方法来定义它实际上会做什么.在您的情况下,您只能在柜台上迭代一次.如果您定义__iter__为返回一个新对象,那么它将使您可以根据需要迭代多次.在你的情况下,Counter已经是一个迭代器,这就是为什么返回它自己是有意义的.