3.默认参数的注意事项
def func(a,l=[]):
l.append(a)
return l
print(func(1)) # [1,]
print(func(2)) # [2,]
print(func(3)) # [3,]
当你的默认参数如果是可变的数据类型,你要小心了。
实际输出
'''
[1]
[1, 2]
[1, 2, 3]
'''
默认参数的陷阱:
def func(name,sex='男'):
print(name)
print(sex)
func('alex')
陷阱只针对于默认参数是可变的数据类型:
def func(name,alist=[]):
alist.append(name)
return alist
ret1 = func('alex')
print(ret1,id(ret1)) # ['alex']
ret2 = func('太白金星')
print(ret2,id(ret2)) # ['太白金星']
如果你的默认参数指向的是可变的数据类型,那么你无论调用多少次这个默认参数,都是同一个。
def func(a, list=[]):
list.append(a)
return list
print(func(10,)) # [10,]
print(func(20,[])) # [20,]
print(func(100,)) # [10,100]
l1 = []
l1.append(10)
print(l1)
l2 = []
l2.append(20)
print(l2)
l1.append(100)
print(l1)
def func(a, list= []):
list.append(a)
return list
ret1 = func(10,) # ret = [10,]
ret2 = func(20,[]) # [20,]
ret3 = func(100,) # ret3 = [10,100]
print(ret1) # [10,] [10,100]
print(ret2) # 20, [20,]
print(ret3) # [10,100] [10,100]