我在Python中創建了一個圖節點類。
每個節點都有單親,多個孩子和屬性。
的實現應該有如下:python對象具有初始化屬性
# graph_test.py
class Node(object):
def __init__(self, name, prop={}):
self.name = name
self.properties = prop
self.parent = None
self.children = []
print "New node:", self.name, self.properties
def add_prop(self, k, v):
self.properties.update({k:v})
print "added prop:", k, v
def add_child(self, n):
self.children.append(n)
n.parent = self
class Foo(object):
def __init__(self, n):
self.node_num = n
self.root_node = None
self.current_node = None
def bas(self):
n = Node("root")
n.add_prop("this_prop_is", "set_only_root_node")
self.root_node = n
return self.root_node
def bar(self):
self.current_node = self.bas()
for i in range(self.node_num):
n = Node(str(i))
self.current_node.add_child(n)
self.current_node = n
if __name__ == '__main__':
f = Foo(5)
f.bar()
在這段代碼中,預計只有根節點,其關鍵是「this_prop_is」的屬性。
然而,執行的結果是象下面這樣:
$ python ./graph_test.py
New node: root {}
added prop: this_prop_is set_only_root_node
New node: 0 {'this_prop_is': 'set_only_root_node'}
New node: 1 {'this_prop_is': 'set_only_root_node'}
New node: 2 {'this_prop_is': 'set_only_root_node'}
New node: 3 {'this_prop_is': 'set_only_root_node'}
New node: 4 {'this_prop_is': 'set_only_root_node'}
所有節點具有相同的鑰匙,甚至我把它添加到僅節點的「根」。我使用python 2.7.6
。
我的問題是:
- 這是一個錯誤?
- 如果這不是一個錯誤,爲什麼會發生這種情況?
- 如何解決這個問題?
謝謝。在C++中,每個函數調用都會對默認參數進行評估,所以它很混亂...... – furushchev