python关于函数形参
2018-12-28 08:04:59来源:博客园 阅读 ()
1.函数的默认参数是可变数据类型时,要尤其注意:如果函数执行过程中默认参数被修改,则永久被修改(下次调用时还会使用上一次被改过的默认参数)
Default parameter values are evaluated from left to right when the function definition is executed. This means that the expression is evaluated once, when the function is defined, and that the same “pre-computed” value is used for each call. This is especially important to understand when a default parameter is a mutable object, such as a list or a dictionary: if the function modifies the object (e.g. by appending an item to a list), the default value is in effect modified. This is generally not what was intended. A way around this is to use None as the default, and explicitly test for it in the body of the function.
1 #示例 2 def whats_on_the_telly(penguin=[]): 3 l=[1,2,3,4] 4 penguin.append("property of the zoo") 5 l.append(666) 6 return penguin, l 7 a,c=whats_on_the_telly() 8 print(a,c) 9 b,d=whats_on_the_telly() 10 print(b,d) 11 #result 12 ['property of the zoo'] [1, 2, 3, 4, 666] 13 ['property of the zoo', 'property of the zoo'] [1, 2, 3, 4, 666] 14 #解决方案 15 def whats_on_the_telly(penguin=None):#修改为None 16 if penguin is None: #增加 17 penguin = [] #增加 18 l=[1,2,3,4] 19 penguin.append("property of the zoo") 20 l.append(666) 21 return penguin, l 22 a,c=whats_on_the_telly() 23 print(a,c) 24 b,d=whats_on_the_telly() 25 print(b,d) 26 #result 27 ['property of the zoo'] [1, 2, 3, 4, 666] 28 ['property of the zoo'] [1, 2, 3, 4, 666]
标签:
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有
上一篇:day 23 模块2
下一篇:python 初识面向对象
- python3基础之“术语表(2)” 2019-08-13
- python3 之 字符串编码小结(Unicode、utf-8、gbk、gb2312等 2019-08-13
- Python3安装impala 2019-08-13
- 小白如何入门 Python 爬虫? 2019-08-13
- python_字符串方法 2019-08-13
IDC资讯: 主机资讯 注册资讯 托管资讯 vps资讯 网站建设
网站运营: 建站经验 策划盈利 搜索优化 网站推广 免费资源
网络编程: Asp.Net编程 Asp编程 Php编程 Xml编程 Access Mssql Mysql 其它
服务器技术: Web服务器 Ftp服务器 Mail服务器 Dns服务器 安全防护
软件技巧: 其它软件 Word Excel Powerpoint Ghost Vista QQ空间 QQ FlashGet 迅雷
网页制作: FrontPages Dreamweaver Javascript css photoshop fireworks Flash