关于内置的__iter__

问题描述 投票:0回答:1

我正在学习python并阅读流利的python书!在遵循一些类实现的同时,我停止了这段代码:

def __iter__(self):
    return iter(self._components)

由于components是一个浮点数组,我的问题是:为什么在组件上调用iter()方法虽然它已经是可迭代的?

python built-in
1个回答
3
投票

documentation doesn't make it very clear,是因为__iter__必须(不应该)返回迭代器,而不是迭代:

% python
Python 3.6.3 (default, Oct  3 2017, 21:45:48) 
[GCC 7.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> class Foo:
...     def __iter__(self):
...         return []
... 
>>> iter(Foo())
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: iter() returned non-iterator of type 'list'
© www.soinside.com 2019 - 2024. All rights reserved.