【问题标题】:Python, Grabbing information from a class object not workingPython,从类对象中获取信息不起作用
【发布时间】:2014-12-03 10:31:39
【问题描述】:

所以我不知道是什么导致了这个错误。不给你看我不知道怎么形容,所以这里是我的代码的相关部分:

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)

问题出在:new.contents 已按计划更改,但 parent.contents 也已更改。发生了什么?

【问题讨论】:

  • 提示:脚本a = []; b = a.append(23); print(b)的输出是什么?
  • 顺便说一句,您创建类级别contentschildren,然后在__init__ 中创建相同变量的对象级别版本。您是否在任何地方使用班级级别列表?如果没有,您应该删除它们。
  • 针对仍然出现的问题更新了问题:现在父项和新项已更改。
  • 已修复,需要在引用之前复制列表。

标签: python list class object append


【解决方案1】:

正如您在评论中提到的那样,您必须将 contents pf 'parent.contents' 复制到 'new_contents' 中。否则,您将通过引用访问列表,这显然不是预期的。

因此,您的“makeNode”函数可以如下开始:

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

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

【讨论】:

  • 实际上,new_content = list(parent.contents) 甚至有效。不过谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-23
  • 2021-05-29
  • 2017-05-10
  • 2018-06-09
  • 1970-01-01
相关资源
最近更新 更多