gpt4 book ai didi

Python:家族级

转载 作者:太空宇宙 更新时间:2023-11-04 03:40:10 25 4
gpt4 key购买 nike

我正在实现一个带有参数名称、职位和 child 的“人”类。函数“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']

但我的实际输出看起来并不像期望的那样。所以,我的问题是:你将如何拯救 children ?在一个简单的列表中?问题显然出在 def desc() 中。感谢您的帮助!

最佳答案

你必须递归 children列表:

def desc(self):
out = []
for kid in self.children:
out.append(kid)
out.extend(kid.desc())
return out

这使用了 desc()当前对象上的方法,然后在每个列出的子对象上调用相同的方法以扩展当前结果列表。这一直持续到遇到没有 child 的对象。

请注意 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()添加 p4out列表,然后用 p4.desc() 的结果扩展列表. p4.desc()添加 p2到它的本地out列表,用 p2.desc() 的结果扩展它, 然后添加 p3out并用 p3.desc() 扩展它等

关于Python:家族级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26869467/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com