要遍历一个对象并打印其子节点,你可以使用递归的方式来实现。以下是一个示例代码:
def print_children(node, level=0):
# 打印当前节点
print(' ' * level + node.name)
# 递归打印子节点
if hasattr(node, 'children'):
for child in node.children:
print_children(child, level + 1)
# 示例对象
class Node:
def __init__(self, name):
self.name = name
self.children = []
# 创建对象树
root = Node('Root')
child1 = Node('Child 1')
child2 = Node('Child 2')
grandchild1 = Node('Grandchild 1')
grandchild2 = Node('Grandchild 2')
grandgrandchild1 = Node('Grandgrandchild 1')
root.children = [child1, child2]
child1.children = [grandchild1]
child2.children = [grandchild2]
grandchild1.children = [grandgrandchild1]
# 遍历对象树并打印子节点
print_children(root)
在上面的示例中,我们定义了一个 Node
类来表示节点,每个节点有一个 name
属性和一个 children
属性,存储其子节点。我们使用递归的方式遍历对象树,并使用缩进来表示节点的层级关系,最后打印每个节点的名称。
输出结果为:
Root
Child 1
Grandchild 1
Grandgrandchild 1
Child 2
Grandchild 2
下一篇:遍历对象并分发键和状态值