Python中带有可选参数的列表追加
可能重复的问题:
Python中的“最小惊讶”:可变默认参数
这件事很奇怪,在Python中,当你用.append()方法时,作为可选参数的列表在函数调用之间是会保持不变的。
def wtf(some, thing, fields=[]):
print fields
if len(fields) == 0:
fields.append('hey');
print some, thing, fields
wtf('some', 'thing')
wtf('some', 'thing')
输出结果:
[]
some thing ['hey']
['hey'] # This should not happen unless the fields value was kept
some thing ['hey']
为什么“fields”这个列表在作为参数时还会包含“hey”?我知道它是局部作用域,因为在函数外我无法访问它,但这个函数却记得它的值。
1 个回答
3
默认值只会被计算一次,所以如果把可变类型作为默认值,就会产生意想不到的结果。你最好像这样做:
def wtf(some, thing, fields = None):
if fields is None:
fields = []