__iter__如何工作? [英] How does __iter__ work?
问题描述
尽管阅读了它,我仍然不太明白 __ iter __
的工作原理。什么是简单的解释?
Despite reading up on it, I still dont quite understand how __iter__
works. What would be a simple explaination?
我见过 def__iter __(self):return self
。我不知道这是如何工作的或步骤如何工作。
I've seen def__iter__(self): return self
. I don't see how this works or the steps on how this works.
推荐答案
迭代器需要定义两个方法: __ iter __()
和 __ next __()
(python2中的 next()
)。通常,对象本身定义 __ next __()
或 next()
方法,因此它只返回迭代器。这会创建一个 iterable ,它本身也是一个迭代器。这些方法由用于
和语句中的
。
An iterator needs to define two methods: __iter__()
and __next__()
(next()
in python2). Usually, the object itself defines the __next__()
or next()
method, so it just returns itself as the iterator. This creates an iterable that is also itself an iterator. These methods are used by for
and in
statements.
Python 2 docs: docs.python.org/2/library/stdtypes.html#iterator-types
Python 2 docs: docs.python.org/2/library/stdtypes.html#iterator-types
这篇关于__iter__如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!