파이썬에서 그래프 노드 클래스를 만들었습니다.
각 노드에는 단일 상위, 여러 하위 및 속성이 있습니다.
구현은 다음과 같이해야합니다 :파이썬 객체는 초기화에 대한 속성을 가지고 있습니다.
# 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