У меня есть простой класс с атрибутом, который может содержать список объектов того же класса
class BoxItem:
def __init__(self, name, **kw):
self.name = name
self.boxItems = []
... #more attributes here
box1 = BoxItem('Normal Box')
box2 = BoxItem('Friendly Box')
box3 = BoxItem('Cool Box')
box4 = BoxItem('Big Box', [box1, box2]) #contains some children
example = BoxItem('Example Box', [box4,box3]) #contains another level of children
Работая с нашим «примером» объекта box, я хотел бы маневрировать в глубине всех возможных дочерних блоков, которые он может иметь, и распечатывать объекты, отформатированные таким образом:
1 Example Box
1.1 Big Box
1.1.1 Normal Box
1.1.2 Friendly Box
1.2 Cool Box
Табуляция между не нужна, просто хочу чтобы четко показать формат дерева. Я могу пройтись по самим объектам и распечатать их названия, но я не могу распечатать передние номера, которые показывают отношения родитель/потомок. (1, 1.1, 1.2...)
Заранее спасибо за помощь:)
Редактировать Вот над чем я работал до сих пор
def print_boxes(box_list):
node_count = 0
for box in box_list:
node_count += 1
print str(node_count)+' '+box.name #prints out the root box
recursive_search(box,node_count)
def recursive_search(box,node_count): #recursive automatically
level = 0
for child in box.boxItems:
level += 1
for x in range(len(child.boxItems)):
print x+1 #this prints out some proper numbers
print "level: "+str(level) #experiment with level
print child.name #prints out child box name
recursive_search(child,node_count) #runs the function again inside the function