Skip to main content
 首页 » 编程设计

Python:家族级

2024年10月25日10zdz8207

我正在实现一个带有参数名称、职位和 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()添加 p4到 out列表,然后用 p4.desc() 的结果扩展列表. p4.desc()添加 p2到它的本地out列表,用 p2.desc() 的结果扩展它, 然后添加 p3至 out并用 p3.desc() 扩展它等