如果我正确理解,在Python中我们可以:
__iter__()
已实现__iter__()
返回自身&__next__()
已实现yield
语句或生成器表达式创建的迭代器。问题:上面是否有始终/从未消耗的类别?
消耗品,我的意思是遍历它们“破坏”可迭代对象。像zip()(可消耗)与range()(不可消耗)。
所有迭代器都被消耗;您可能不这样认为的原因是,当您将类似
for x in [1,2,3]:
该for
环路为您创建幕后一个新的迭代。事实上,list
是不是一个迭代器; iter([1,2,3])
返回类型list_iterator
,而不是列表本身的东西。
关于您在评论中链接到的示例,而不是
class PowTwo:
def __init__(self, max=0):
self.max = max
def __iter__(self):
self.n = 0
return self
def __next__(self):
if self.n <= self.max:
result = 2 ** self.n
self.n += 1
return result
else:
raise StopIteration
在返回它的行为中有修改迭代器的副作用,我会做类似的事情
class PowTwoIterator:
def __init__(self, max=0):
self.max = max
self._restart()
def _restart(self):
self._n = 0
def __iter__(self):
return self
def __next__(self):
if self._n <= self.max:
result = 2 ** self._n
self._n += 1
return result
else:
raise StopIteration
现在,唯一可以修改对象状态的方法就是显式地进行修改(甚至也不应该轻易修改,因为_n
和_restart
都被标记为不属于公共接口)。
名称的更改提醒您,这首先是一个迭代器,而不是可以提供独立迭代器的可迭代器。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句