为什么类需要__iter __()返回迭代器? [英] Why does a class need __iter__() to return an iterator?

查看:172
本文介绍了为什么类需要__iter __()返回迭代器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么一个类需要定义 __ iter __()返回自身以获取该类的迭代器?

Why does a class need to define __iter__() returning self, to get an iterator of the class?

class MyClass:
    def __init__(self):
        self.state = 0

    def __next__(self):
        self.state += 1
        if self.state > 4:
            raise StopIteration
        return self.state

myObj = MyClass()
for i in myObj:
    print(i)

控制台日志:

Traceback (most recent call last):
   for i in myObj:
TypeError: 'MyClass' object is not iterable

答案 https://stackoverflow.com/a/9884259/4515198 ,说


迭代器是具有下一个(Python 2)或 __ next __ (Python 3)方法。

An iterator is an object with a next (Python 2) or __next__ (Python 3) method.

添加以下内容的任务:

def __iter__(self):
   return self

是返回迭代器,或定义 __ next __()方法的类的对象。

is to return an iterator, or an object of the class, which defines the __next__() method.

但是,这不是返回 __ new __()已经完成的MyClass对象(定义 __ next __()方法)的任务。 / code>方法,当在行myObj = MyClass()上实例化MyClass时?

But, isn't the task of returning an object of MyClass (which defines the __next__() method) already done by the __new__() method, when MyClass is instantiated in the line myObj = MyClass() ?

不会定义 __ next __()方法,本身就是迭代器吗?

Won't the objects of a class defining __next__() method, be iterators by themselves?

我研究了在__iter__方法中返回self有什么用?构建基本的Python迭代器,但我仍然无法理解 __ iter __()方法返回的原因

I have studied the questions What is the use of returning self in the __iter__ method? and Build a Basic Python Iterator, but I am still unable to understand the reason for having an __iter__() method returning self.

推荐答案

为什么 __ iter __()方法为何的问题的答案必需的是,对于 for循环,始终要通过在对象上调用 iter() 来获得迭代器。这就是为什么即使迭代器本身也需要一个 __ iter __()方法来处理for循环的原因。在 for 调用 iter()之后,它将在生成的迭代器上调用 __ next __()以获取值。

The answer to the question of why the __iter__() method is necessary is that for for-loops always start by calling iter() on an object to get an iterator. That is why even iterators themselved need an __iter__() method to work with for-loops. After for calls iter(), then it calls __next__() on the resulting iterator to obtain a value.

创建可迭代对象和迭代器的规则为:

The rules for creating iterables and iterators are:

1)可迭代对象具有返回的 __ iter __()方法

1) Iterables have an __iter__() method that returns an iterator.

2)迭代器具有 __ next __()方法,该方法返回一个值,更新状态并引发 Stopperation 完成。

2) Iterators have a __next__() method that returns a value, that updates the state, and that raises StopIteration when complete.

3)迭代器本身具有一个 __ iter __()方法,该方法返回 self

3) Iterators themselves have a __iter__() method that returns self. That means that all iterators are self-iterable.

对于具有 __ iter __()的迭代器,最后一条规则的好处

>>> s = 'hello world'
>>> it = iter(s)
>>> next(it)
'h'
>>> next(it)
'e'
>>> list(it)     # Doesn't start from the beginning
['l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']

这是另一个示例,它依赖于迭代器是可自行迭代的而无需重新启动:

Here's another example that depends on iterators being self-iterable without restarting:

>>> s = 'hello world'
>>> it = iter(s)
>>> list(zip(it, it))
[('h', 'e'), ('l', 'l'), ('o', ' '), ('w', 'o'), ('r', 'l')]

注意:

1)进行迭代的另一种方法是提供一个 __ getitem __()方法,该方法接受连续索引并引发 IndexError 完成。这就是在Python 2中迭代 str 对象的方式。

1) An alternative way to make an iterable is to supply a __getitem__() method that accepts consecutive indices and raises IndexError when complete. This is how str objects iterated in Python 2.

2)有些对象(例如文件)是它们自己的迭代器。这意味着您可以直接在文件对象上调用 next()。这也意味着文件不能具有多个独立的迭代器(文件对象本身具有跟踪文件中位置的状态)。

2) Some objects like files are their own iterator. That means that you can call next() directly on a file object. It also means that files cannot have multiple, independent iterators (the file object itself has the state tracking the position within the file).

3)上述迭代器设计模式不是特定于Python的。这是许多OOP语言的通用设计模式: https://en.wikipedia.org/wiki/Iterator_pattern

3) The iterator design pattern described above isn't Python specific. It is a general purpose design pattern for many OOP languages: https://en.wikipedia.org/wiki/Iterator_pattern

这篇关于为什么类需要__iter __()返回迭代器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆