在不使用“()"的情况下,将字典值作为当访问键时要调用的函数. [英] Dictionary value as function to be called when key is accessed, without using "()"

查看:114
本文介绍了在不使用“()"的情况下,将字典值作为当访问键时要调用的函数.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字典,它的值有时是字符串,有时是函数.对于作为函数的值,是否有一种方法可以执行该函数而无需在访问键时显式键入()?

I have a dictionary that has values sometimes as strings, and sometimes as a functions. For the values that are functions is there a way to execute the function without explicitly typing () when the key is accessed?

示例:

d = {1: "A", 2: "B", 3: fn_1}
d[3]() # To run function

我想要:

d = {1: "A", 2: "B", 3: magic(fn_1)}
d[3] # To run function

推荐答案

另一种可能的解决方案是创建一个实现此行为的自定义词典对象:

Another possible solution, is to create a custom dictionary object that implements this behavior:

>>> class CallableDict(dict):
...     def __getitem__(self, key):
...         val = super().__getitem__(key)
...         if callable(val):
...             return val()
...         return val
...
>>>
>>> d = CallableDict({1: "A", 2: "B", 3: lambda: print('run')})
>>> d[1]
'A'
>>> d[3]
run

一个也许更惯用的解决方案将是使用:

A perhaps more idiomatic solution would be to use try/except:

def __getitem__(self, key):
    val = super().__getitem__(key)
    try:
        return val()
    except TypeError:
        return val

但是请注意,上面的方法确实是为了完善.我不推荐使用它. 如前所述在注释中删除,它将掩盖该功能引发的TypeError.您可以测试TypeError的确切内容,但是到那时,最好使用LBYL样式.

Note however the method above is really for completness. I would not reccomend using it. As pointed out in the comments, it would mask TypeError's raised by the function. You could test the exact content of TypeError, but at that point, you'd be better of using the LBYL style.

这篇关于在不使用“()"的情况下,将字典值作为当访问键时要调用的函数.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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