gpt4 book ai didi

python - Python 类初始化中的意外结果

转载 作者:行者123 更新时间:2023-11-28 20:52:17 25 4
gpt4 key购买 nike

我写了下面的代码:

class node:
def __init__(self, title, series, parent):
self.series = series
self.title = title
self.checklist = []
if(parent != None):
self.checklist = parent.checklist
self.checklist.append(self)

当我创建这样的对象时:

a = node("", s, None)
b = node("", s, a)
print a.checklist

出乎意料的是,它同时显示了 a 和 b 对象作为 print 语句的输出。我是 python 的新手。所以,可能有一些愚蠢的错误。

谢谢。

最佳答案

您执行 self.checklist = parent.checklist 这意味着两个实例共享同一个列表。它们都将自己添加到其中,因此当您打印它时,您会看到这两个实例。

也许您想制作一份父列表的副本? self.checklist = parent.checklist[:]

关于python - Python 类初始化中的意外结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7066181/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com