引言
不知道小伙伴们有没有遇到过一个问题,就是 Python
编译器提示我们默认参数是可变的情况,这里我们来对这个问题进行一下说明。
正文
先来看一段代码:
def append(number, number_list=[]):
number_list.append(number)
print(number_list)
return number_list
# Below are 3 calls to the `append` function and their expected and actual outputs:
append(5) # expecting: [5], actual: [5]
append(7) # expecting: [7], actual: [5, 7]
append(2) # expecting: [2], actual: [5, 7, 2]
"""
result:
[5]
[5, 7]
[5, 7, 2]
"""
结果很夸张,我们每一次调用,都会累计上次掉用后的结果,很明显会留一个 bug
的隐患给我们。
那么如何解决这个问题呢?只需要将代码改为如下形式即可。
def append(number, number_list=None):
if number_list is None:
number_list = []
number_list.append(number)
print(number_list)
return number_list
# Below are 3 calls to the `append` function and their expected and actual outputs:
append(5) # expecting: [5], actual: [5]
append(7) # expecting: [7], actual: [5, 7]
append(2) # expecting: [2], actual: [5, 7, 2]
"""
result:
[5]
[7]
[2]
"""
如果大家觉得有用,就请点个赞吧~