以实现一个深度优先方式遍历树形节点的生成器为例:
class Node:def __init__(self, value):self._value = valueself._children = []def __repr__(self):return f"Node({self._value})"def add_child(self, node):self._children.append(node)def __iter__(self):return iter(self._children)def depth_first(self):yield selffor node in self:yield from node.depth_first()# 定义根节点root = Node(0)# 定义子节点child1 = Node(1)child2 = Node(2)root.add_child(child1)root.add_child(child2)# 添加孙节点child1.add_child(Node(3))child2.add_child(Node(4))child2.add_child(Node(5))for node in root.depth_first():print(node) # Node(0) Node(1) Node(3) Node(2) Node(4) Node(5)
