当我运行这段代码:追加对象列表修改对象
class Node:
children = []
num_children = 0
isleaf = True
def __init__(self,name):
print("constructor called for " + name)
self.name = str(name)
def add_child(self,child_node):
print("adding child called "+child_node.name+ " to "+ self.name)
print("I ("+self.name+ ") have " + str(len(self.children)) + " children")
print("checking: " + child_node.name + " reports " + str(len(child_node.children)) + " children")
#cc = copy.deepcopy(child_node)
self.children.append(child_node)
#self.children.append(1)
#self.children[0] = child_node
print("checking again: " + child_node.name + " reports " + str(len(child_node.children)) + " children")
self.isleaf = False
self.num_children = self.num_children +1
print("I ("+self.name+ ") now have " + str(len(child_node.children)) + " children")
root = Node("a")
testn = Node("b")
root.add_child(testn)
print(root.children[0].name)
我得到这样的输出:
constructor called for a
constructor called for b
adding child called b to a
I (a) have 0 children
checking: b reports 0 children
checking again: b reports 1 children
I (a) now have 1 children
b
为什么代码行:
self.children.append(child_node)
添加孩子(B
)以及父母(A
)?
我希望它只是个孩子添加到父(A
)
你想让'children'成为一个类变量吗? – 2016-11-04 11:35:26
是的,孩子应该是节点的成员。我正在尝试并未能实现树 –
如果您希望'children'是一个实例变量,请将其设为一个。请参阅下面的答案。 – 2016-11-04 11:37:04