如何在不修改其成员的情况下将 Class 对象附加到列表中?
class Node:
def __init__(self, name, type, children=[]):
self.name = name
self.type = type
self.children = children
def add_child(self, child_node):
self.children.append(child_node)
def printNode(self, indent = 0):
print(self.name + " has children " + str(len(self.children)))
#for child in self.children: print(child, indent + 4)
if __name__ == "__main__":
A = Node("A", "company")
B = Node("B", "department")
B.printNode()
A.add_child(B)
B.printNode()
该append()
函数将节点 B 添加到自身,即使它应该只将其添加到节点 A 的子列表中,从输出中可以明显看出
B has children 0
B has children 1