我正在努力实现让儿童进入树形结构的可能性。
以下是我想要的例子。
到目前为止我做了什么。
class Children(list):
def __init__(self, l):
list.__init__(l)
self.l = l
@property
def children(self):
_children = []
for child in self.l:
_children.extend(child.children)
return Children(_children)
class Person:
def __init__(self):
self._children = Children([])
def add_child(self, child):
self._children += [child]
@property
def children(self):
return self._children
me = Person()
sister = Person()
brother = Person()
father = Person()
cousin = Person()
uncle = Person()
grandpa = Person()
ancient_grandpa = Person()
father.add_child(me)
father.add_child(sister)
father.add_child(brother)
uncle.add_child(cousin)
grandpa.add_child(father)
grandpa.add_child(uncle)
ancient_grandpa.add_child(grandpa)
print ancient_grandpa # ancient_grandpa
print ancient_grandpa.children # [grandpa]
print ancient_grandpa.children.children # [father, uncle] but got []
print ancient_grandpa.children.children.children # [me, sister, brother, cousin] but got []
请注意,这只是一个最小的工作示例。事实上,我的树比这更深。
答案 0 :(得分:3)
使用树时,最常见的是使用递归来提取数据并从树中进行修改。
你可能会做类似的事情:
class Person(object):
def __init__(self, name):
self.name = name
self.children = []
def get_generation_n(self, n):
if n <= 0:
return []
if n == 1:
return self.children
generation = []
for child in self.children:
generation += child.get_generation_n(n - 1)
return generation
def add_child(self, person):
self.children.append(person)
def __repr__(self):
return self.name
grandpa = Person('Grand-Pa')
p1 = Person('p1')
p2 = Person('p2')
p3 = Person('p3')
p4 = Person('p4')
p5 = Person('p5')
p3.add_child(p5)
p3.add_child(p4)
p1.add_child(p2)
grandpa.add_child(p1)
grandpa.add_child(p3)
print(grandpa.get_generation_n(1)) # prints [p1, p3]
print(grandpa.get_generation_n(2)) # prints [p2, p4, p5]
事实上,你只需要一个班级。对于孩子来说,只是另一个人。