python 中 a=b=class_name(value) 和 a=class_name(value) b=class_name(value) 之间的区别 [不重复]

Difference between a=b=class_name(value) and a=class_name(value) b=class_name(value) in python [not duplicate]

在下面的代码中,如果我使用tree = parent = node(leaf_1) treeparent 总是有相同的打印结果;然而,如果我将该行更改为 tree = node(leaf_1)parent = node(leaf_1),那么 treeparent 将不相同。

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_1)tree = node(leaf_1); parent = node(leaf_1) 有不同的输出?

提前致谢!

这个 tree = parent = node(leaf_1) 创建了一个 node 对象并将其分配给 treeparent 而这个 tree = node(leaf_1); parent = node(leaf_1) 创建了两个不同的 node 对象并将它们分别分配给 treeparent


parent.add(leaf_2)
parent.add(leaf_3)

此处您仅将 leaf_2leaf_3 添加到 parent。这可能是第二种情况输出的原因。