我使用参数name,title和children来实现一个" person" -class。 功能" desc"应该返回家谱下面的人员名单。
到目前为止,我已经做到了这一点:
class Person():
def __init__(self, name, title, children=None):
self.name = name
self.title = title
if children is None:
self.children = []
else:
self.children = children
def desc(self):
self.out = []
if self.children:
for kid in self.children:
self.out.append(kid)
return self.out
p1 = Person("p1", "test")
p2 = Person("p2", "test", children = [p1])
p3 = Person("p3", "test")
p4 = Person("p4", "test", children = [p2, p3])
p5 = Person("p5", "boss", children = [p4])
print [person.title for person in p5.desc()]
# desired output:
# ['test', 'test', 'test','test']
print [person.name for person in p5.desc()]
# desired output:
# ['p4', 'p2', 'p1', 'p3']
但是我的实际输出看起来不像想要的那样。 所以,我的问题是:你如何拯救孩子?在一个简单的清单?问题显然在def desc()中。 谢谢你的帮助!
答案 0 :(得分:2)
您必须递归children
列表:
def desc(self):
out = []
for kid in self.children:
out.append(kid)
out.extend(kid.desc())
return out
这在当前对象上使用desc()
方法,然后在每个列出的子节点上调用相同的方法来扩展当前结果列表。这种情况一直持续到遇到没有孩子的物体为止。
请注意,out
不需要是实例的属性;我改为保留了一个局部变量。
这会产生您的预期输出:
>>> class Person():
... def __init__(self, name, title, children=None):
... self.name = name
... self.title = title
... if children is None:
... self.children = []
... else:
... self.children = children
... def desc(self):
... out = []
... for kid in self.children:
... out.append(kid)
... out.extend(kid.desc())
... return out
...
>>> p1 = Person("p1", "test")
>>> p2 = Person("p2", "test", children = [p1])
>>> p3 = Person("p3", "test")
>>> p4 = Person("p4", "test", children = [p2, p3])
>>> p5 = Person("p5", "boss", children = [p4])
>>> print [person.title for person in p5.desc()]
['test', 'test', 'test', 'test']
>>> print [person.name for person in p5.desc()]
['p4', 'p2', 'p1', 'p3']
因此p5.desc()
将p4
添加到out
列表,然后使用p4.desc()
的结果扩展列表。 p4.desc()
将p2
添加到其本地out
列表中,使用p2.desc()
的结果进行扩展,然后将p3
添加到out
并使用p3.desc()
等扩展它