Python函数默认参数的一个小陷阱

def  foo(a1, args  =  []):
    
print   " args before %s "   %  (args)
    args.insert(0, 
10 )
    args.insert(0, 
99999 )
    
print   " args %s  "   %  (args)

def  main():
    foo(
' a ' )
    foo(
' b ' )

if   __name__   ==   " __main__ " :

    main()


以上小程序会有如下输出:

 

args before  =  []
args 
=  [ 99999 10
args before 
=  [ 99999 10 ]
args 
=  [ 99999 10 99999 10

 

 

按照通常的理解,第二次调用的args应该为默认值[],但为什么会变成上一次的结果呢?

查阅Python manual有如下的说法:

Default parameter values are evaluated when the function definition is executed. This means that the expression is evaluated once, when the function is defined, and that that same “pre-computed” value is used for each call. This is especially important to understand when a default parameter is a mutable object, such as a list or a dictionary: if the function modifies the object (e.g. by appending an item to a list), the default value is in effect modified. This is generally not what was intended. A way around this is to use None as the default, and explicitly test for it in the body of the function, e.g.:

 

def  whats_on_the_telly(penguin = None):
    
if  penguin  is  None:
        penguin 
=  []
    penguin.append(
" property of the zoo " )
    
return  penguin

 

 

至此,原因已经很清楚了:函数中的参数默认值是一个可变的list, 函数体内修改了原来的默认值,而python会将修改后的值一直保留,并作为下次函数调用时的参数默认值


转自:http://www.cnblogs.com/ukessi/archive/2010/01/25/python-function-default-parameter-value-problem.html,留作学习


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值