python 默认参数放后面_空字典作为python函数中的关键字参数的默认值:字典似乎不被初始化为{}在后续调用?...

Here's a function. My intent is to use keyword argument defaults to make the dictionary an empty dictionary if it is not supplied.

>>> def f( i, d={}, x=3 ) :

... d[i] = i*i

... x += i

... return x, d

...

>>> f( 2 )

(5, {2: 4})

But when I next call f, I get:

>>> f(3)

(6, {2: 4, 3: 9})

It looks like the keyword argument d at the second call does not point to an empty dictionary, but rather to the dictionary as it was left at the end of the preceding call. The number x is reset to three on each call.

Now I can work around this, but I would like your help understanding this. I believed that keyword arguments are in the local scope of the function, and would be deleted once the function returned. (Excuse and correct my terminology if I am being imprecise.)

So the local value pointed to by the name d should be deleted, and on the next call, if I don't supply the keyword argument d, then d should be set to the default {}. But as you can see, d is being set to the dictionary that d pointed to in the preceding call.

What is going on?

Is the literal {} in the def line in the enclosing scope?

This behavior is seen in 2.5, 2.6 and 3.1.

解决方案>>> def f(i, d=None, x=3):

... if not d:

... d={}

... d[i] = i*i

... x += i

... return x,d

...

>>> f(2)

(5, {2: 4})

>>> f(3)

(6, {3: 9})

>>>

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值