我正在学习如何通过设计家谱来制作列表。下面是我提出的一种方法,但我在打印结果时遇到问题。例如:
如果A有2个孩子,B& C... 然后B有2个孩子,D& E. .. 而C只有孩子,F ...
我希望打印结果:[A,[B,[D,E]],[C,[F]]]
感谢我的代码中的任何改进,如何打印上述结果的建议,或以图形形式打印。
class FamilyTree:
def __init__(self, root):
self.name = [root]
nmbr = int(input("How many children does " + root + " have?"))
if nmbr is not 0:
for i, child in enumerate(range(nmbr)):
name = input("What is one of " + root + "'s child's name?")
setattr(self, "child{0}".format(i), FamilyTree(name))
r = print(FamilyTree('A'))
答案 0 :(得分:0)
您可以使用print()
函数调用的__str__
方法:
class FamilyTree:
def __init__(self, root):
self.name = root
self.children = []
nmbr = int(input("How many children does " + root + " have? "))
if nmbr is not 0:
for i, child in enumerate(range(nmbr)):
name = input("What is one of " + root + "'s child's name? ")
self.children.append(FamilyTree(name))
def __str__(self):
return '[' + self.name + ''.join(', ' + str(c) for c in self.children) + ']'
r = print(FamilyTree('A'))
答案 1 :(得分:0)
将对象创建与输入和输出分开是个好主意。此外,使用setattr
会使编写输出变得更加困难。
这是一个解决方案,允许您创建一个FamilyTree
,无论是否有来自用户的阅读输入:
class FamilyTree:
def __init__(self, root, childs = []):
self.name = root
self.childs = childs
def read(self):
nmbr = int(input("How many children does " + self.name + " have? "))
if nmbr is not 0:
for _ in range(nmbr):
name = input("What is one of " + self.name + "'s child's name? ")
child = FamilyTree(name)
child.read()
self.childs.append(child)
def __repr__(self):
if len(self.childs) == 0:
return str("{}".format(self.name))
else:
return str("{}, {}".format(self.name, self.childs))
# creates a FamilyTree directly so we can test the output
r = FamilyTree(
'A',
[
FamilyTree(
'B',
[FamilyTree('C'), FamilyTree('C')]
),
FamilyTree(
'C',
[FamilyTree('F')]
)
]
)
# or read input from the user
# r = FamilyTree('A')
# r.read()
print(r)
输出
A, [B, [C, C], C, [F]]