简体   繁体   English

使用字典从字符串调用函数

[英]Using a dict to call functions from a string

I would like the first two words of a user input string to be read as function arguments for where to save the string.我希望将用户输入字符串的前两个单词作为函数参数读取,以用于保存字符串的位置。 I've settled on using a dict instead of many if statements, but I'm not sure how to structure the dict.我已经决定使用 dict 而不是许多 if 语句,但我不确定如何构建 dict。

I believe this is a correct start:我相信这是一个正确的开始:

input: "question physics What happens to atoms when they are hit by photons?"输入:“问题物理学当原子被光子击中时会发生什么?” result: program saves the input in location questions\\physics结果:程序将输入保存在 location questions\\physics

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

The two words (each being a "get_id" in the example) will designate where to save the text.这两个词(在示例中每个词都是“get_id”)将指定保存文本的位置。 This example seems to be what I'm looking for, but I'm not sure how to change it for my case.这个例子似乎是我正在寻找的,但我不确定如何为我的情况改变它。

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

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

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

Let me know if I'm going about this logically or if it doesn't make sense.让我知道我是否符合逻辑或没有意义。 Thanks!谢谢!

You will need to define the functions separately from the dictionary您将需要与字典分开定义函数

For example:例如:

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

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

you can then call the function with its keyword:然后,您可以使用其关键字调用该函数:

function_dict["get_id"]()

but you can also do this without a dictionary if the keyword is the same as the function name:但是如果关键字与函数名称相同,您也可以在没有字典的情况下执行此操作:

globals()["get_id"]()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM