Python Recursion through objects and child objects, Print child depth numbers

后端 未结 2 1915
孤独总比滥情好
孤独总比滥情好 2021-01-05 00:51

I have a simple class with an attribute that can contain a list of objects of the same class

class BoxItem:
  def __init__(self, name, **kw):
      self.name         


        
2条回答
  •  北荒
    北荒 (楼主)
    2021-01-05 01:21

    You have two options:

    1. Keep track of the additional information as an additional parameter in your recursion, e.g. myRecursiveFunction(..., ancestry=[])
    2. Have each BoxItem keep track of its parent, whenever it is embedded in a BoxItem (in the __init__ constructor, set child.parent = self for each child). This is bad if you plan to have a BoxItem in more than one box.

提交回复
热议问题