有时,有一个默认参数是空列表似乎很自然。然而Python produces unexpected behavior in these situations
例如,如果我有一个函数:
def my_func(working_list=[]):
working_list.append("a")
print(working_list)
第一次调用它时,默认值将起作用,但之后的调用将更新现有列表(每次调用一个"a"
),并打印更新的版本
那么,用什么样的方法来获得我想要的行为(每次通话都有一个新的列表)
Tags:
其他答案已经提供了所要求的直接解决方案,但是,由于这是新Python程序员的一个常见陷阱,因此有必要添加Python为何以这种方式运行的解释,这在Mutable Default Arguments下的The Hitchhikers Guide to Python中得到了很好的总结:
The docs表示应该使用
None
作为默认值,并在函数体中显式使用test for it在这种情况下,这并不重要,但您可以使用对象标识来测试无:
您还可以利用python中如何定义布尔运算符或:
但是,如果调用方给您一个空列表(计为false)作为工作列表,并希望您的函数修改他给它的列表,那么这将意外地发生
相关问题 更多 >
编程相关推荐