【问题标题】:Why are values from a dict not being returned even if keys are present when passing a function as default?为什么在默认传递函数时即使存在键也不会返回来自dict的值?
【发布时间】:2022-11-03 20:31:38
【问题描述】:

我对以下行为感到有些困惑。我正在从字典中检索值,这样如果一个键不存在,我会调用一个函数来创建该值并将其插入到字典中。我通过dictionary.get 方法的default 参数来做到这一点。问题是即使值已经存在于字典中,默认函数也会被调用。 真是令人难以置信。关于为什么会发生这种情况的任何想法?

dictionary = {}
def load_default(key):
    print("Inside function")
    value = "world"
    dictionary[key] = value
    return value

print(dictionary) 
'{}' #empty dict, everything ok
value = dictionary.get("hello", load_default("hello"))
'Inside function' # we ask for "hello", which does not exist so we call load_default
print(dictionary) 
"{'hello': 'world'}" # the dict now contains de key "hello"
value = dictionary.get("hello", load_default("hello"))
'Inside function' # we ask for "hello" again, but load_default is called instead ("Inside function" is printed) I would expect the dict to return only the value and not call `load_default`

在给定的示例中,我希望字典返回值 world 而不调用 load_default 函数

【问题讨论】:

    标签: python dictionary


    【解决方案1】:

    在给定的示例中,我希望字典在不调用 load_default 函数的情况下返回值 world。

    在执行dictionary.get("hello", load_default("hello")) 时,Python 首先评估传递给.get() 方法的表达式作为参数,然后使用从提供的参数的评估中获得的值调用该方法。

    第一个传递的表达式是一个值“hello”,因此它可以按原样传递给.get()。第二个作为参数传递的表达式是load_default("hello"),它需要被评估为一个值,因为它是对函数的调用。要获得一个值,必须执行函数,然后函数的结果返回值将作为第二个参数传递给.get()

    在那个阶段,.get() 还没有执行,所以假设只有当键不在字典中时函数才会运行的假设是错误的,会导致混淆。

    换句话说,.get() 将在它的参数作为值传递之后执行,因为函数调用不是一个值,它需要被评估为一个值,所以load_default() 将在每次调用.get() 时运行。

    【讨论】:

    • 啊,我明白你的意思了。您的意思是调用load_default 是为了生成稍后将传递给.get 函数以决定要做什么的参数,对吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-04
    • 1970-01-01
    • 2013-02-18
    • 1970-01-01
    相关资源
    最近更新 更多