关于内置的__iter__

时间:2017-12-23 20:03:46

标签: python built-in

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

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

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

1 个答案:

答案 0 :(得分: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'