有没有一种方法可以将功能用作字典的值?

时间:2020-07-12 11:24:21

标签: python python-3.x list function dictionary

我必须通过从用户处获得关于要执行的字符串操作的输入来执行多项操作。所以我在考虑使用一个字典,其中函数名是键,值是函数本身。我还想将参数传递给函数。有没有办法做到这一点? 这就是我想做的:

def fin1():
    #some context
    pass

def fin2():
    #some context
    pass

def fin3():
    #some context
    pass

def fin4():
    #some context
    pass

test_dic = {"1": fin1, "2": fin2, "3": fin3, "4": fin4}

some_string = "123123wafds"

result_string = ""
for single_str in some_string:
    if single_str in test_dic:
        test_dic[single_str]()
    else:
        result_string += single_str

我知道这行不通,我还想提供用户输入的参数。有办法吗?

谢谢。

1 个答案:

答案 0 :(得分:7)

只需从函数中删除()

a = [] # an empty list
inp = input() # which function to apply?
arg = int(input()) # the argument corresponding to the function.

# a dictionary mapping all the functions to the names
func_dict = {"append":a.append, "pop":a.pop, "extend": a.extend} 

这样,您将获得该函数的引用而不是其结果。

编辑:然后使用func_dict['append'](arg)来调用该函数。请注意,如果您的函数具有不同数量的参数,则此解决方案可能会失败,因此您可能必须在调用函数之前进行检查。