使用字典从字符串中调用函数
Using a dict to call functions from a string
我希望将用户输入字符串的前两个词读取为函数参数,用于确定字符串的保存位置。我已经决定使用 dict 而不是许多 if 语句,但我不确定如何构建 dict。
我认为这是一个正确的开始:
输入:"question physics What happens to atoms when they are hit by photons?"
结果:程序将输入保存在位置questions\physics
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}
)
}
让我知道我是否在逻辑上进行此操作,或者它是否没有意义。谢谢!
您需要从字典中单独定义函数
例如:
def get_id():
... the function's code ...
function_dict = { "get_id":get_id, ... }
然后您可以使用其关键字调用该函数:
function_dict["get_id"]()
但如果关键字与函数名称相同,您也可以在没有字典的情况下执行此操作:
globals()["get_id"]()
我希望将用户输入字符串的前两个词读取为函数参数,用于确定字符串的保存位置。我已经决定使用 dict 而不是许多 if 语句,但我不确定如何构建 dict。
我认为这是一个正确的开始:
输入:"question physics What happens to atoms when they are hit by photons?" 结果:程序将输入保存在位置questions\physics
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}
)
}
让我知道我是否在逻辑上进行此操作,或者它是否没有意义。谢谢!
您需要从字典中单独定义函数
例如:
def get_id():
... the function's code ...
function_dict = { "get_id":get_id, ... }
然后您可以使用其关键字调用该函数:
function_dict["get_id"]()
但如果关键字与函数名称相同,您也可以在没有字典的情况下执行此操作:
globals()["get_id"]()