python 手动迭代iter/next
- 2019 年 10 月 11 日
- 筆記
with open('/etc/passwd') as f: while True: line = next(f, None) if line is None: break print(line, end='')
items = [1, 2, 3] Get the iterator it = iter(items) # Invokes items.iter() Run the iterator next(it) # Invokes it.next() 1 next(it) 2 next(it) 3 next(it) Traceback (most recent call last): File "<stdin>", line 1, in <module> StopIteration
类实现迭代iter
class Node: def init(self, value): self._value = value self._children = []
def __repr__(self): return 'Node({!r})'.format(self._value) def add_child(self, node): self._children.append(node) def __iter__(self): return iter(self._children)
Example
if name == 'main': root = Node(0) child1 = Node(1) child2 = Node(2) root.add_child(child1) root.add_child(child2) # Outputs Node(1), Node(2) for ch in root: print(ch