python中a=b=class_名称(值)和a=class_名称(值)b=class_名称(值)之间的差异[不重复]

python中a=b=class_名称(值)和a=class_名称(值)b=class_名称(值)之间的差异[不重复],python,class,object,instance,repr,Python,Class,Object,Instance,Repr,在下面的代码中,如果我使用tree=parent=node(leaf_1) 树和父项始终具有相同的打印结果;然而,如果我将该行更改为tree=node(leaf_1)和parent=node(leaf_1),则树和父将不相同 class node(object): def __init__(self, value): self.value = value self.children = [] def __repr__(self, level=0):

在下面的代码中,如果我使用
tree=parent=node(leaf_1)
父项
始终具有相同的打印结果;然而,如果我将该行更改为
tree=node(leaf_1)
parent=node(leaf_1)
,则
将不相同

class node(object):
    def __init__(self, value):
        self.value = value
        self.children = []
    def __repr__(self, level=0):
        ret = "\t"*level+repr(self.value)+"\n"
        for child in self.children:
            ret += child.__repr__(level+1)
        return ret
    def add(self, nod):
        self.children.append(node(nod))
leaf_1 = [1,4,3]
leaf_2 = [2,5,3]
leaf_3 = [4,4,3]

tree = parent = node(leaf_1) #### code 1
parent.add(leaf_2)
parent.add(leaf_3)
print(tree)
print(parent)
在上述代码中,两个
print
的输出相同,如下所示:

output 1:
[1, 4, 3]
    [2, 5, 3]
    [4, 4, 3]
但是,如果我将
tree=parent=node(leaf_1)
更改为
tree=node(leaf_1)
parent=node(leaf_1)
,则输出:

output 2:
[1, 4, 3]

[1, 4, 3]
    [2, 5, 3]
    [4, 4, 3]
我的问题

为什么
tree=parent=node(leaf\u 1)
tree=node(leaf\u 1);父节点=节点(叶1)
是否有不同的输出


提前谢谢

tree=parent=node(leaf_1)
,创建一个
node
对象,并将其分配给
tree
parent
以及此
tree=node(leaf_1);parent=node(leaf_1)
创建了两个不同的
节点
对象,并将它们分别分配给
父对象


parent.add(叶_2)
添加(叶_3)

这里您只将
leaf_2
leaf_3
添加到
parent
。这可能是第二种情况下输出的原因。

如果写入
tree=parent=node(leaf_1)
tree
parent
指向相同的
节点。使用
tree=node(leaf_1)
parent=node(leaf_1)
tree
parent
指向两个不同的
节点
。谢谢@Peter,另一个问题,你知道如果我使用
self.children.append(nod)
而不是
self.children.append(nod)),为什么会出错吗
添加方法中?错误为“TypeError:应为0个参数,得到1个”您的
leaf_1
leaf_2
leaf_3
不是
节点,它们是正常的
列表。在
\uuuuu repr\uuu
函数中,循环遍历子项,然后对它们调用
\uuuuuu repr\uu
。但是当您调用
列表
函数而不是
节点
\uu报告
函数时,您会得到“预期的0参数”错误。我猜您希望
leafs
成为
节点
。(顺便说一句,如果你有第二个问题,请创建一个新帖子。)谢谢@nobleknight,这一点现在很清楚了。另一个问题,您知道如果在
add
方法中使用
self.children.append(nod)
而不是
self.children.append(node(nod))
,为什么会出现错误吗?错误为“TypeError:应为0个参数,得到1”?谢谢