请解释Python如何执行以下代码:

2024-09-27 21:35:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我对下面代码生成的输出很感兴趣。 有人能解释一下为什么python在第三次执行函数调用时打印[1,5]而不仅仅是[5],以及它是python中的一个特性还是一个bug吗

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

Tags: def特性bug代码生成print函数调用arg1arg2
1条回答
网友
1楼 · 发布于 2024-09-27 21:35:03

关于这个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.

相关问题 更多 >

    热门问题