参考教程:
测试代码:
#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类型的修改后指向对象发生变化的认识存在遗漏