以实现一个深度优先方式遍历树形节点的生成器为例:

    1. class Node:
    2. def __init__(self, value):
    3. self._value = value
    4. self._children = []
    5. def __repr__(self):
    6. return f"Node({self._value})"
    7. def add_child(self, node):
    8. self._children.append(node)
    9. def __iter__(self):
    10. return iter(self._children)
    11. def depth_first(self):
    12. yield self
    13. for node in self:
    14. yield from node.depth_first()
    15. # 定义根节点
    16. root = Node(0)
    17. # 定义子节点
    18. child1 = Node(1)
    19. child2 = Node(2)
    20. root.add_child(child1)
    21. root.add_child(child2)
    22. # 添加孙节点
    23. child1.add_child(Node(3))
    24. child2.add_child(Node(4))
    25. child2.add_child(Node(5))
    26. for node in root.depth_first():
    27. print(node) # Node(0) Node(1) Node(3) Node(2) Node(4) Node(5)