如何使用[]作为python中命名的函数参数的默认值? [英] How do I use [] as a default value for a named function argument in python?
问题描述
可能重复:
Python中的最少惊讶:可变默认参数
我有这个代码
class Test(object):
def __init__(self, var1=[]):
self._var1 = var1
t1 = Test()
t2 = Test()
t1._var1.append([1])
print t2._var1
[[1]]。所以清楚t1._var1和t2._var1寻址相同的列表。如果我放
and I get "[[1]]" as the result. So clearly t1._var1 and t2._var1 are addressing the same list. If I put
t3 = Test()
print t3._var1
那么我得到[[1]]。所以var1 = []似乎永久绑定var1到一些列表。我尝试复制列表,
then I get "[[1]]" as well. So var1=[] seems to permanently bind var1 to the some list. I tried copying the list,
def __init__(self, var1=copy([])):
但结果相同,因此命名参数的表达式在init被调用之前被评估, var1一个空列表的副本,然后在实例之间共享。
but got the same result, so the expression for the named argument appears to be evaluated prior to init being called, and it just gave var1 a copy of the empty list which was then shared amongst the instances.
那么如何使用[]作为命名参数的默认值?
So how do I use [] as a default value for a named argument?
推荐答案
如果你想让每个对象都有一个对象,你不能直接使用 []
空列表。我倾向于使用一个工作:
You can't use []
directly if you want each object to have an empty list. I tend to use a work around:
def __init__(self, var1=None):
if var1 is None:
var1 = []
....
t工作如果 var1
可以无
,则需要使用不同的对象。
Naturally this won't work if var1
can be None
, you would need to use a different object.
这篇关于如何使用[]作为python中命名的函数参数的默认值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!