当我尝试在特定实例中更改类属性时,所有其他实例的属性也会更改。即使我创建了该类的全新实例,其属性也会自动更改
我正在尝试实现树型数据结构。我认为问题与继承有关,但我无法弄清楚。
#here I'm making a simple class to represent
#the node of a tree
class Node:
def __init__(self, children=[]):
self.children = children
root = Node()
branch = Node()
#now I make branch a child of root
root.children.append(branch)
#and it works...
root.children
>>>[<pexp2.Node object at 0x7f30146d3438>]
#...but for some reason branch now also has a child
branch.children
>>>[<pexp2.Node object at 0x7f30146d3438>]
#and now I make a whole new instance that
#isn't connected to root or branch
isolated_node = Node()
#and somehow it also has a child that I never gave it
isolated_node.children
>>>[<pexp2.Node object at 0x7f30146d3438>]
我不知道为什么每个节点都会生一个孩子。如果只指定一个节点,我只希望它有子节点。在上面的代码中,root是唯一应该有一个孩子的根(或者就是我的想法)。
答案 0 :(得分:2)
您正面临所谓的可变默认参数,请尝试以下操作:
class Node:
def __init__(self, children=None):
if children is None:
children = []
self.children = children
基本上,您遇到此问题是因为: