Python,从类对象获取信息不起作用

2024-04-16 05:12:25 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我不知道是什么导致了这个错误。我不知道如何描述它而不给你看,所以下面是我代码的相关部分:

class Node(object):
    def __init__(self, contents, children):
        self.contents = contents
        self.children = children


def makeNode(district, parent):
    new_contents = parent.contents
    new_contents.append(district)
    new = Node(new_contents, [])
    parent.children.append(new)
    return new


root = Node([], [])
data = [[1,1,'r'],[1,2,'d'],[1,2,'r'],[1,4,'d']]
makeNode(data, root)

问题是:新建.contents是按计划改变的,但也是如此父目录. 发生什么事了?你知道吗


Tags: 代码selfnodenewdatadef错误contents
1条回答
网友
1楼 · 发布于 2024-04-16 05:12:25

正如您在评论中提到的,您必须复制内容pf'父目录'转换为'新内容'。否则,您将通过引用访问列表,这显然不是预期的。你知道吗

因此,“makeNode”函数可以如下启动:

def makeNode(district, parent):
    new_content = copy.deepcopy(parent.contents)
    ...

我希望,我能为以后的读者澄清一下。。。;)

相关问题 更多 >