1.下面代码的输出结果是什么
1 def aaa(val,list=[]): 2 list.append(val) 3 return list 4 5 a1=aaa(10) 6 a2=aaa(123,[]) 7 a3=aaa('abc') 8 9 print(a1) 10 print(a2) 11 print(a3)
结果是:
[10, 'abc'] [123] [10, 'abc']
函数的默认列表list只在函数定义的时候创建一次,以后都是那个
2.函数延迟绑定
1 def multipliers(): 2 return [lambda x:i*x for i in range(4)] 3 4 print([m(2) for m in multipliers()])
结果是:
[6, 6, 6, 6]
python闭包的延迟绑定,内部函数被调用时,参数的值在函数内部进行查找,当multipliers调用时,for循环已经执行完毕,i的值就是3
1 def n(): 2 return [lambda x,i=i: i*x for i in range(4)] 3 5 print([m(2) for m in n()])
[0, 2, 4, 6]