使用dict从字符串调用函数

问题描述 投票:1回答:1

我希望将用户输入字符串的前两个单词作为函数参数读取,以保存字符串。我已经决定使用dict而不是很多if语句,但我不确定如何构造dict。

我相信这是一个正确的开始:

输入:“问题物理当光子被光子撞击时会发生什么?”结果:程序将输入保存在位置问题\物理中

raw_entry = input("Enter text in the following format: type subtype text")
instructions = raw_entry.split()[:2]

这两个单词(在示例中均为“get_id”)将指定保存文本的位置。这个例子似乎是我正在寻找的,但我不知道如何根据我的情况改变它。

function_dict = {'get_id': 
                        (
                        # function
                        requests.get,

                        # tuple of arguments
                        (url + "/users/" + user,), 

                        # dict of keyword args
                        {'headers': self.headers}
                        )
                 }

如果我在逻辑上或者没有意义的话,请告诉我。谢谢!

python string dictionary key-value dispatch
1个回答
1
投票

您需要与字典分开定义函数

例如:

def get_id():
    ... the function's code ...

function_dict = { "get_id":get_id, ... }

然后,您可以使用其关键字调用该函数:

function_dict["get_id"]()

但如果关键字与函数名称相同,您也可以在没有字典的情况下执行此操作:

globals()["get_id"]()
© www.soinside.com 2019 - 2024. All rights reserved.