Python类初始化中出现意外结果

2024-04-25 02:25:23 发布

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

我写了以下代码:

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还不熟悉。所以,可能有一些愚蠢的错误。你知道吗

谢谢你。你知道吗


Tags: 对象代码selfnonenodeiftitleinit
2条回答

小心切片符号[:] 这将复制列表,但如果列表包含其他列表,则这些列表本身将通过引用复制,而不是作为新对象。你知道吗

例如:

>>> a = [1,2,3]
>>> b = [4,5,6]
>>> x = [a,b]
>>> y = x[:]
>>> x
[[1, 2, 3], [4, 5, 6]]
>>> y
[[1, 2, 3], [4, 5, 6]]
>>> a.append(66)
>>> x
[[1, 2, 3, 66], [4, 5, 6]]
>>> y
[[1, 2, 3, 66], [4, 5, 6]]

     ^^^^^^^^^  unexpectedly y has an updated a inside it, even though we copied it off.


>>> import copy
>>> y = copy.deepcopy(x)
>>> a.append(77)
>>> x
[[1, 2, 3, 44, 55, 66, 77], [4, 5, 6]]
>>> y
[[1, 2, 3, 44, 55, 66], [4, 5, 6]]

                     ^^^^^ y is a seperate object and so are all its children

您可能对使用id(y)查看对象y的内存地址感兴趣

您需要self.checklist = parent.checklist,这意味着两个实例共享同一个列表。它们都将自己添加到它中,所以当您打印它时,您可以看到这两个实例。你知道吗

也许你想复印一份家长名单?self.checklist = parent.checklist[:]

相关问题 更多 >