简体   繁体   English

Python,无法从类对象获取信息

[英]Python, Grabbing information from a class object not working

So I have no idea what's causing this error. 因此,我不知道是什么导致了此错误。 I don't know how to describe it without showing you, so here's the relevant part of my code: 我不知道如何在不向您展示的情况下描述它,所以这是我的代码的相关部分:

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)

Here's the problem: new.contents is changed as planned, but so is parent.contents. 这是问题所在:new.contents按计划更改,parent.contents也按计划更改。 What happened? 发生了什么?

As you've mentioned it in your comment, you've got to copy the contents pf 'parent.contents' into 'new_contents'. 正如您在评论中提到的那样,您必须将pf'parent.contents'的内容复制到'new_contents'中。 Otherwise, you're accessing the list by reference, which is obviously not what is intended. 否则,您将通过引用访问列表,这显然不是您想要的。

So, your 'makeNode' function could start as follows: 因此,您的“ makeNode”函数可以按如下所示启动:

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

I hope, I could clear things up for later readers... ;) 我希望我可以为以后的读者澄清一下...;)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM