當我運行這段代碼:追加對象列表修改對象
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