python - 请解释python如何执行以下代码:
问题描述
我对以下代码生成的输出很感兴趣。谁能向我解释为什么 python 在第三次执行函数调用时打印 [1,5] 而不仅仅是 [5],以及它是 Python 中的功能还是错误?
def funn(arg1, arg2=[]):
arg2.append(arg1)
print(arg2)
funn(1)
funn(2, [3, 4])
funn(5)
解决方案
这里有一篇很好的文章。但为了更好地理解,我对你的函数做了一个小的修改,以更好地可视化问题。
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.
推荐阅读
- sql - 在进行两个表的内部连接时查找列的最大值
- java - Apache Solr 处理数十万个请求
- javascript - 为什么在全局范围内的 for-of 循环中使用 const 会抛出 TypeError,但在函数内它可以工作?
- java - Coin Change - Java 未能通过示例 3
- python - python virtualenv中硒的chrome web驱动程序错误
- xslt - 遍历 XSLT 中的列表并将其分配给 Java 对象
- python-3.x - 在线程上运行函数会出错
- python - Psycopg2 不仅接受 None (Nonetype) 作为使用 %s 时可以为 Null 的单元格条目,但不接受 f 字符串
- java - 在没有 Class.forName() 或系统属性的情况下如何加载 JDBC 驱动程序?
- hybris - 使用 Smartedit 的本地化 nm 关系时如何修复 ClassCastException?