我对以下代码生成的输出很感兴趣。 谁能解释为什么python打印[1,5]而不仅仅是[5]它第三次执行函数调用时,如果它是Python中的一个特性或错误?
def funn(arg1, arg2=[]):
arg2.append(arg1)
print(arg2)
funn(1)
funn(2, [3, 4])
funn(5)
答案 0 :(得分:3)
关于这个here有一篇很好的文章。但为了更好地理解,我对你的功能进行了一些小修改,以更好地可视化问题。
def funn(arg1, arg2=[]):
print(id(arg2))
arg2.append(arg1)
print(arg2)
funn(1) # here you will get printed an id of arg2
funn(2, [3, 4]) # here it's a different id of arg2 because it's a new list
funn(5) # here you will see that the id of the arg2 is the same as in the first function call.