频道栏目
首页 > 资讯 > Python > 正文

python的默认参数问题测试代码解析

18-07-27        来源:[db:作者]  
收藏   我要投稿

测试代码:

#default parameter of list
def power(l=[]):
 l.append('END')
 print(l,id(l))
 return l
power()
power()

#default parameter of int
def plus(a=0):
 a+=10
 print(id(a),a)
 return a
plus()
plus()

#defualt parameter of str
def sayhello(who='you'):
 print(who,'say hello',id(who))
sayhello()
sayhello()

#test list
l1=[1,2,3]
print(l1,id(l1))
l1.append(4)
print(l1,id(l1))

#test str
s1='hello'
print(s1,id(s1))
s1='go'
print(s1,id(s1))

#test int
i1=5
print(i1,id(i1))
i1=10
print(i1,id(i1))

输出:

['END'] 413969891080
['END', 'END'] 413969891080
1435266352 10
1435266352 10
you say hello 413969881664
you say hello 413969881664
[1, 2, 3] 413969982088
[1, 2, 3, 4] 413969982088
hello 413969882112
go 413969900128
5 1435266192
10 1435266352

分析:

参考教程中指出使用默认参数的一个陷阱在于以list这种可修改的变量作为默认参数调用后值可能会被修改,已验证。同时测试了int和str两种类型,str为不可修改类型,hello 和 go即可说明,s1指向不同的对象,内存地址发生了变化;int同str类似,若修改变量值,其指向对象也变化。因此使用int,str等不可修改的变量作为默认参数是可靠的。

tips:

之所以记录下来时因为对int类型的修改后指向对象发生变化的认识存在遗漏

相关TAG标签
上一篇:函数重载原理及介绍
下一篇:编译型与解释型编程语言的区别
相关文章
图文推荐

关于我们 | 联系我们 | 广告服务 | 投资合作 | 版权申明 | 在线帮助 | 网站地图 | 作品发布 | Vip技术培训 | 举报中心

版权所有: 红黑联盟--致力于做实用的IT技术学习网站