Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/278.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-core/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python类初始化中出现意外结果_Python - Fatal编程技术网

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

Python类初始化中出现意外结果,python,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.

我编写了以下代码:

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[:]

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

例如:

>>> 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应该引发AttributeError如果parent=None,我认为应该在if语句中。而且,使用
父项不是None
而不是
=并且不要在if语句中使用偏执语句(只有一个条件)。对不起。那是一个复制错误。是的。成功了。谢谢。我不知道这种类似静态的行为。那我们怎么做才能复制它呢?我不知道你的意思。如果您希望创建对象的未连接副本,并且不100%确信该对象没有子对象,请使用copy.deepcopy。通常,每次需要不相关的副本时,都要使用deepcopy。但一般来说,复制可变对象通常是一种迹象,您可以用另一种方式简化它