- 论坛徽章:
- 0
|
对于非数值类型的默认参数,只会在第一次调用时进行求值(取地址)操作,后面的所有调用都发生在同一个位置的对象上。只有字符串类型不受此限制,因为string本身是不可变的(immutable)的,每一次修改它都会创建一个新的对象。
按照luffy.deng的方法,你可以打印出L的id,这样就比较清楚了。
或者你用下面的代码来看看:
- def f(a, L=[]):
- L.append(a)
- print("L = {0} and the L's id is {1}".format(L,id(L)))
- return L
- def F(a, L=None):
- if L is None:
- L = []
- L.append(a)
- print("L = {0} and the L's id is {1}".format(L,id(L)))
- return L
- def main():
- print 'f(1): ', f(1)
- print 'f(2, [3]): ', f(2, [3])
- print 'f(4): ', f(4)
- print 'f(5, [6]): ', f(5, [6])
- print 'f(7): ', f(7)
- print 'F(1): ', F(1)
- print 'F(2,[3]): ', F(2,[3])
- print 'F(4): ', F(4)
- print 'F(5, [6]): ', F(5, [6])
- if __name__ == '__main__':
- main()
复制代码 f(1): L = [1] and the L's id is 140296258680304 #可以看到,当不指定L的值时,使用默认参数,L的id是304
[1]
f(2, [3]): L = [3, 2] and the L's id is 140296258100832 #当指定L的值为[3]时,地址变成了832
[3, 2]
f(4): L = [1, 4] and the L's id is 140296258680304 #可以看到,当不指定L的值时,使用默认参数,L的id是304, 所以再计算f(4)的时候,就会结果就是[1, 4]
[1, 4]
f(5, [6]): L = [6, 5] and the L's id is 140296258100832
[6, 5]
f(7): L = [1, 4, 7] and the L's id is 140296258680304
[1, 4, 7]
F(1): L = [1] and the L's id is 140296258100832
[1]
F(2,[3]): L = [3, 2] and the L's id is 140296258100832
[3, 2]
F(4): L = [4] and the L's id is 140296258100832
[4]
F(5, [6]): L = [6, 5] and the L's id is 140296258100832
[6, 5] |
|