关于内置 __iter__
About the built-in __iter__
我正在学习 python 并且正在阅读 python 书!
在执行一些 class 实现时,我停在了这段代码:
def __iter__(self):
return iter(self._components)
components
是一个浮点数组,我的问题是:为什么要在组件上调用 iter()
方法,尽管它已经是一个可迭代的?
而documentation doesn't make it very clear,是因为__iter__
必须(不是应该)return 迭代器,而不是可迭代:
% 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'
我正在学习 python 并且正在阅读 python 书! 在执行一些 class 实现时,我停在了这段代码:
def __iter__(self):
return iter(self._components)
components
是一个浮点数组,我的问题是:为什么要在组件上调用 iter()
方法,尽管它已经是一个可迭代的?
而documentation doesn't make it very clear,是因为__iter__
必须(不是应该)return 迭代器,而不是可迭代:
% 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'