使用字典映射从键盘输入调用函数(Using dictionary mapping to call functions from Keyboard Input)

编程入门 行业动态 更新时间:2024-10-23 11:26:52
使用字典映射从键盘输入调用函数(Using dictionary mapping to call functions from Keyboard Input)

我在字典中有几个预定义的函数:

dict = { 'test1':test1(), 'test2':test2(), 'test3':test3() }

在这一点上,我已经有一个问题:创建字典后,这些函数会自动运行 - 为什么是这样的,我该如何避免它?

最终,我的目标是输入例如“test2”并获得执行的功能(只是以受控方式执行,而不是像上面那样一次执行)。 首先我想使用eval ,但是所有人都反对,现在我明白了。 但是,替代方案是什么? 我试过了

def select_function(): try: return dict[input("Type in function ")] except KeyError: raise ValueError('Invalid input!') select_function()

以及只是

dict.get(input("Type in function "), 'Invalid input!')

但是如果我输入正确的函数,两者都会返回空行 。 如果我输入错误信息,则会收到错误消息,因此我的命令应该可以正常工作。 我也知道我的函数的工作原理,正如我所说的,它们在我创建字典后被执行,并且只打印一个问候语(每个函数用于测试)。

我做错什么了吗? 有没有其他的方式来调用函数没有eval() ?在此先感谢。

I have several pre-defined functions in a dictionary:

dict = { 'test1':test1(), 'test2':test2(), 'test3':test3() }

At this point I already have a question: after creating the dictionary these functions run automatically - why is that and how can I avoid it?

Ultimately, my goal is to type in e.g. "test2" and get the function executed (just the one in a controlled manner, not everything at once like above). First I wanted to use eval, but everyone advised against it, which I understand now. But what is the alternative? I tried

def select_function(): try: return dict[input("Type in function ")] except KeyError: raise ValueError('Invalid input!') select_function()

as well as just

dict.get(input("Type in function "), 'Invalid input!')

But both return an empty line if I type in the correct function. If I type in a wrong one I get my error message, therefore my command should work in general. I also know my functions work because, as I said, they get executed after I create the dictionary and they only print a greeting (a different one for each function for testing).

Did I do something wrong? Is there some other way to call functions without eval()?Thanks in advance.

最满意答案

这样做

dict = { 'test1':test1, 'test2':test2, 'test3':test3 }

然后

return dict[input("Type in function")]

如果你想调用这个函数,Just

return dict[input("Type in function")]()

Do it like

dict = { 'test1':test1, 'test2':test2, 'test3':test3 }

Then

return dict[input("Type in function")]

If you want to call that function, Just

return dict[input("Type in function")]()

更多推荐

本文发布于:2023-08-04 04:06:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1409370.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字典   函数   键盘输入   dictionary   mapping

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!