Possible Duplicate:
least astonishment in python: the mutable default argument
我想了解python__init__
构造函数的行为和含义。如果有一个可选参数,并且尝试将现有对象设置为新对象,则会保留和复制现有对象的可选值。
看一个例子:
在下面的代码中,我试图创建一个包含节点的树结构,可能还有许多子节点。在第一个类NodeBad
中,构造函数有两个参数,值和任何可能的子级。第二个类NodeGood
只接受节点的值作为参数。两者都有一个addchild
方法来向节点添加子节点。
使用NodeGood
类创建树时,它按预期工作。然而,当对NodeBad
类执行相同的操作时,似乎只能添加一次子类!
下面的代码将产生以下输出:
Good Tree
1
2
3
[< 3 >]
Bad Tree
1
2
2
[< 2 >, < 3 >]
克帕萨?
下面是一个例子:
#!/usr/bin/python
class NodeBad:
def __init__(self, value, c=[]):
self.value = value
self.children = c
def addchild(self, node):
self.children.append(node)
def __str__(self):
return '< %s >' % self.value
def __repr__(self):
return '< %s >' % self.value
class NodeGood:
def __init__(self, value):
self.value = value
self.children = []
def addchild(self, node):
self.children.append(node)
def __str__(self):
return '< %s >' % self.value
def __repr__(self):
return '< %s >' % self.value
if __name__ == '__main__':
print 'Good Tree'
ng = NodeGood(1) # Root Node
rootgood = ng
ng.addchild(NodeGood(2)) # 1nd Child
ng = ng.children[0]
ng.addchild(NodeGood(3)) # 2nd Child
print rootgood.value
print rootgood.children[0].value
print rootgood.children[0].children[0].value
print rootgood.children[0].children
print 'Bad Tree'
nb = NodeBad(1) # Root Node
rootbad = nb
nb.addchild(NodeBad(2)) # 1st Child
nb = nb.children[0]
nb.addchild(NodeBad(3)) # 2nd Child
print rootbad.value
print rootbad.children[0].value
print rootbad.children[0].children[0].value
print rootbad.children[0].children
可变的默认参数是一个混乱的来源。
看这个答案:"Least Astonishment" and the Mutable Default Argument
问题是,可选参数的默认值只是一个实例。例如,如果您说
def __init__(self, value, c=[]):
,那么每次调用代码使用可选参数时,相同的列表[]
都将被传递到方法中。所以基本上,对于可选参数的默认值,应该只使用不可变的日期类型,如
None
。例如:然后可以在方法体中创建一个新列表:
相关问题 更多 >
编程相关推荐