我在字典中有几个预定义的函数:
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")]()更多推荐
发布评论