dict.get() - 即使成功,默认arg也被评估 [英] dict.get() - default arg evaluated even upon success

查看:127
本文介绍了dict.get() - 即使成功,默认arg也被评估的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么 dict.get(key [,default])中的默认值 评估即使密钥在字典中?

Why is the default in dict.get(key[, default]) evaluated even if the key is in the dictionary?

>>> key = 'foo'
>>> a={}
>>> b={key:'bar'}
>>> b.get(key, a[key])
Traceback (most recent call last):
  File "<pyshell#5>", line 1, in <module>
    b.get(key, a[key])
KeyError: 'foo'


推荐答案

在任何函数调用中,参数在执行调用之前进行求值。

在这种情况下, dict.get() 也不例外...

As in any function call, the arguments are evaluated before the call is executed.
In this case dict.get() is no exception...

这篇关于dict.get() - 即使成功,默认arg也被评估的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆