我在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