Python定义函数时参数有默认值问题解决
作者:Python探索牛 时间:2023-02-10 21:58:49
这篇文章主要介绍了Python定义函数时参数有默认值问题解决,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
在定义函数的时候,如果函数的参数有默认值,有两种类型的参数,一种是整数,字符串这种不可变类型,另一种是列表这种可变类型,对于第一种情况没有什么特殊的地方,但是对于可变类型,有一个微妙的小陷阱。
可变类型以及小陷阱:
def append_item(item, list1=[]):
list1.append(item)
return list1
print(append_item((1))) # [1]
print(append_item((2))) # [1, 2]
print(append_item((6))) # [1, 2, 6]
list2 = [6, 7]
print(append_item(1, list2)) # [6, 7, 1]
print(append_item(9, list2)) # [6, 7, 1,9]
问题:为什么会输出[1,2],[1,2,6],很明显使用默认参数的情况下,每调用一次append_item,都在之前得list1基础上添加元素。但是不使用默认值,就没有这种情况了,这是为什么呢?
原因:在创建上面的函数时,list1参数被设置为引用一个新的列表,之后,在仅使用第一个参数调用该函数(即第二个使用默认参数)时,默认的列表都将是函数本身创建时指定的那个列表,因此将不会再有新的列表得以创建。
我们所期待的是,在每次仅使用第一个参数调用该函数时,都会创建一个新的空列表,下面进行改动:
def append_item(item, list1=[]):
if not list1:
list1 = []
list1.append(item)
return list1
print(append_item((1))) # [1]
print(append_item((2))) # [2]
print(append_item((6))) # [6]
list2 = [6, 7]
print(append_item(1, list2)) # [6, 7, 1]
print(append_item(9, list2)) # [6, 7, 1,9]
来源:https://www.cnblogs.com/djdjdj123/p/12051310.html
标签:Python,定义,函数,参数,默认,值
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
python strip() 函数和 split() 函数的详解及实例
2021-07-03 09:34:56
Python判断文件或文件夹是否存在的三种方法
2021-04-25 21:53:06
Go 实现 WebSockets和什么是 WebSockets
2024-04-26 17:15:42
![](https://img.aspxhome.com/file/2023/5/134395_0s.png)
Django项目实战之用户头像上传与访问的示例
2021-01-27 04:28:16
![](https://img.aspxhome.com/file/2023/7/99087_0s.png)
python实现读取excel文件中所有sheet操作示例
2022-04-25 15:00:36
![](https://img.aspxhome.com/file/2023/4/127144_0s.png)
Flash对象在(x)HTML中的格式和参数及安全性
2010-04-01 11:55:00
![](https://img.aspxhome.com/file/UploadPic/20104/1/634042425122417500_1-54s.png)
Python编程学习之如何判断3个数的大小
2022-03-06 18:10:04
Windows11使用Cpython 编译文件报错 error: Unable to find vcvarsall.bat 完美解决方法
2021-03-14 19:03:19
![](https://img.aspxhome.com/file/2023/6/131446_0s.jpg)
Python绘制1000响大地红鞭炮动态效果
2021-08-21 20:44:26
![](https://img.aspxhome.com/file/2023/9/66009_0s.gif)
网页视频播放器程序代码(通用代码),支持avi,wmv,asf,mov,rm,ra,ram等
2008-07-16 11:56:00
基于idea操作hbase数据库并映射到hive表
2024-01-19 23:22:57
![](https://img.aspxhome.com/file/2023/7/110867_0s.png)
15个应该掌握的Jupyter Notebook使用技巧(小结)
2023-12-14 15:25:05
![](https://img.aspxhome.com/file/2023/9/124379_0s.png)
selenium+python自动化测试之使用webdriver操作浏览器的方法
2023-06-28 03:04:47
python pygame实现五子棋小游戏
2021-10-31 13:39:23
PyTorch策略梯度算法详情
2022-12-20 14:35:12
![](https://img.aspxhome.com/file/2023/7/86617_0s.png)
如何在不同版本的SQL Server中存储数据
2009-01-15 13:06:00
大家都对vertical-align的各说各话
2008-06-19 12:11:00
![](https://img.aspxhome.com/file/UploadPic/20086/19/2008619121517533s.gif)
Python编程实现的简单神经网络算法示例
2022-01-06 05:53:17
![](https://img.aspxhome.com/file/2023/1/98321_0s.jpg)
安装MySQL错误归档处理
2008-12-22 14:50:00
Pandas如何对Categorical类型字段数据统计实战案例
2023-03-01 20:02:26