python中函数默认值使用注意点详解
作者:jingxian 时间:2021-01-26 12:36:44
当在函数中定义默认值时,值初始化只会进行一次,就是执行到def methodname时执行。看下面代码:
from datetime import datetime
def test(t=datetime.today()):
print t
if __name__ == "__main__":
test()
test()
两次方法调用输出的时间都为同一个值,而不是我们预想当前执行时间。对于上面这种情况,建议用下面的方式实现:
from datetime import datetime
def test2(t = None):
if t is None:
t = datetime.today()
print t
if __name__ == "__main__":
test()
test()
标签:python,函数,默认值
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
在pycharm中使用git版本管理以及同步github的方法
2021-12-08 01:59:58
![](https://img.aspxhome.com/file/2023/5/83655_0s.jpg)
pyinstaller打包python3.6和PyQt5中各种错误的解决方案汇总
2021-01-13 18:58:48
很有创意的鼠标指针风筝
2007-09-22 09:24:00
![](https://img.aspxhome.com/file/UploadPic/20079/22/200792292550972s.jpg)
Pandas Shift函数的基础入门学习笔记
2023-02-16 20:46:12
使用python实现微信小程序自动签到功能
2021-05-30 10:04:11
![](https://img.aspxhome.com/file/2023/0/64660_0s.jpg)
python实现定时发送邮件
2022-12-20 07:49:49
python正则表达式re.match()匹配多个字符方法的实现
2023-07-30 08:25:16
ASp使用AspJpeg组件制作透明文字水印
2008-01-15 20:25:00
![](https://img.aspxhome.com/file/UploadPic/20081/15/2008115202930732s.jpg)
常用java正则表达式的工具类
2023-06-14 09:16:46
PHP伪协议基本原理介绍
2023-05-30 00:24:11
![](https://img.aspxhome.com/file/2023/9/55369_0s.png)
python实现文件分片上传的接口自动化
2022-06-29 03:39:41
python实现复制大量文件功能
2023-09-03 16:42:54
Python translator使用实例
2021-02-09 22:40:24
TensorFlow索引与切片的实现方法
2022-11-08 16:00:12
![](https://img.aspxhome.com/file/2023/7/97517_0s.png)
python文件夹分区的实现方法实例
2022-03-04 02:05:39
![](https://img.aspxhome.com/file/2023/2/97382_0s.png)
Python排序搜索基本算法之选择排序实例分析
2023-10-05 20:01:12
![](https://img.aspxhome.com/file/2023/7/110367_0s.jpg)
用ASP读取/写入UTF-8编码格式的文件
2007-08-20 09:29:00
pytorch中的transforms模块实例详解
2022-04-25 19:50:58
Django单元测试工具test client使用详解
2021-04-11 22:25:58
Pyinstaller打包Scrapy项目的实现步骤
2022-05-01 18:07:02
![](https://img.aspxhome.com/file/2023/6/112786_0s.png)