Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/304.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/svn/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python中的迭代器(iter())函数。_Python_Iterator - Fatal编程技术网

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

Python中的迭代器(iter())函数。,python,iterator,Python,Iterator,对于字典,我可以使用iter()迭代字典的键 y = {"x":10, "y":20} for val in iter(y): print val 当我有如下迭代器时 class Counter: def __init__(self, low, high): self.current = low self.high = high def __iter__(self): return self def next(

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

y = {"x":10, "y":20}
for val in iter(y):
    print val
当我有如下迭代器时

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
为什么我不能这样用呢

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

但是这样呢

for c in Counter(3, 8):
    print c
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

所有这些都很好,除了打字错误——你可能是说:

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

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

我认为您的实际问题是,当您打算
打印I


iter()
用于获取给定对象上的迭代器。如果你有一个
\uuuuu iter\uuuuu
方法来定义iter的实际功能。在您的情况下,只能在计数器上迭代一次。如果您定义了
\uuuuu iter\uuuuu
来返回一个新对象,它将使它成为一个新对象,这样您就可以根据需要进行多次迭代。在您的例子中,计数器已经是一个迭代器,这就是为什么返回它自己是有意义的。

当iter(x)和x给出相同的结果时,iter()的作用是什么?感谢您找到输入错误。
iter
将对象转换为迭代器(即,它返回对象的迭代器)。当对象已经是迭代器时,它什么也不做,
\uuuuu iter\uuuu
只返回自身<代码>对于x中的i
实际上是在为您调用
iter
;因为这是不必要的(它已经是一个迭代器了),迭代器的
\uuuu iter\uuuu
调用会自动返回。这里是Python 2.6
x = Counter(3,8)
for i in x:
    print x