当我运行此代码时:
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
)
答案 0 :(得分:0)
将children = []
移至__init__
以使其成为实例成员。现在它是类成员:
def __init__(self, name):
self.children = []
self.num_children = 0
self.isleaf = True
答案 1 :(得分:0)
那是因为您将子项定义为类变量而不是实例变量。这意味着children
并非真正属于root
或testn
,而是属于Node
类本身。
要解决此问题,只需将children = []
替换为self.children = []
内的__init__
。