【问题标题】:Empty list in Python class constructor causes errorPython类构造函数中的空列表导致错误
【发布时间】:2021-05-13 15:11:04
【问题描述】:

我正在创建一个简单的树,其中每个节点在 Python 中都有任意数量的子节点,并且我创建了一个 Node 类来帮助我。 每个节点都包含对其父节点 (int) 和任何子节点 (list) 的引用。

但是,向 Node 构造函数的参数显式添加一个空列表给我带来了奇怪的结果,我想解释一下为什么当列表显式或未显式放入构造函数参数时此行为会发生变化:

实施 #1:

class Node:
    def __init__(self, value, parent, children=[]):
        self.parent = parent
        self.value = value 
        self.children = children

实施 #2:

class Node:
    def __init__(self, value, parent):
        self.parent = parent
        self.value = value 
        self.children = []

填充“节点”数组:

parents = [4,-1,4,1,1]
nodes = [None] * n
for i in range(n):
    nodes[i] = Node(i, parents[i])

存储每个节点的父属性:

tree = Tree()
for i, node in enumerate(nodes):
    parent_id = node.parent
    if parent_id == -1: 
        tree.root = nodes[i]
    else:
        nodes[parent_id].children.append(node.value)

print([(node.value, node.children) for node in nodes])

通过实施#1,我得到:

[(0, [0, 2, 3, 4]), (1, [0, 2, 3, 4]), (2, [0, 2, 3, 4]), (3, [0, 2, 3, 4]), (4, [0, 2, 3, 4])]

但是通过实施 #2 我(正确)得到:

[(0, []), (1, [3, 4]), (2, []), (3, []), (4, [0, 2])]

为什么不一样?我不明白为什么即使使用ifelse 语句,每个节点的列表也是完全填充的。 感谢所有帮助,包括如果您认为有更好的方法可以做到这一点。

【问题讨论】:

    标签: python-3.x class tree nodes constructorargument


    【解决方案1】:

    默认参数在定义函数时绑定一次,因此Node 的每个对象在您的第一个实现中都会获得相同的列表对象

    在函数运行时评估局部变量,因此self.children=[] 在每个对象中分配一个新列表。

    如果您想允许可选的children 参数,更好的方法是

    class Node:
        def __init__(self, value, parent, children=None):
            self.parent = parent
            self.value = value 
            self.children = children or []
    

    这使用None 作为默认值。 or 运算符允许我们在参数为真时选择 children,如果为假则选择空列表。

    来自the docs

    【讨论】:

    • 令人难以置信的快速响应,而且非常清晰。谢谢 :) 这个一般想法是否有名称,例如何时发生参数绑定?
    • 非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多