【发布时间】:2016-05-12 03:33:53
【问题描述】:
此代码旨在创建图形实现。但是,所有节点“self.children”都链接到内存中的同一个列表,因此将子节点添加到其中的任何节点都会将其添加到所有节点。我这辈子都想不通为什么会发生这种情况,我做过很多次这样的课,都没有遇到过这样的问题。
我的意思是,仅仅因为您在默认值中定义了一个列表并不意味着我当时就在那里制作了一个列表,是吗?这令人困惑......
class DescisionNode(object):
def __init__(self,data,score,childs=[]):
self.data = data
self.score = score
self.parent = None
self.children = childs
def getTop(self):
if self.parent == None:
return self
else:
return self.parent.getTop()
def getEnds(self):
out = []
if len(self.children)==0:
return [self]
else:
print(self,self.children)
for n in self.children:
out += n.getEnds()
return out
def add(self, newNode):
if newNode.parent == None:
newNode.parent = self
else:
raise Exception("Parent already exists.")
if newNode is self:
raise Exception("self may not be child")
self.children.append(newNode)
【问题讨论】:
-
向前(下一个节点)构建列表比向后(父节点)要容易得多
标签: python list python-3.x graph init