首页 > 解决方案 > 请解释python如何执行以下代码:

问题描述

我对以下代码生成的输出很感兴趣。谁能向我解释为什么 python 在第三次执行函数调用时打印 [1,5] 而不仅仅是 [5],以及它是 Python 中的功能还是错误?

def funn(arg1, arg2=[]):
    arg2.append(arg1)
    print(arg2)
funn(1)
funn(2, [3, 4])
funn(5)

标签: pythonfunctionscopenamespacesinterpreter

解决方案


这里有一篇很好的文章。但为了更好地理解,我对你的函数做了一个小的修改,以更好地可视化问题。

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.

推荐阅读