我需要的是获取变量的东西,如果变量是函数的名称,则将调用该函数.我不是试图从模块中获取函数,而是从程序本身中获取函数
例:
def foo():
print("Foo")
callfunction = input("What function do you want to call? ")
callfunction() ## Not sure what to put here but but lets say callfunction is foo.
Run Code Online (Sandbox Code Playgroud)
我不想要这样的东西,因为我有很多功能:
if callfunction == "Foo"
Foo()
else:
print("No function with that name")
Run Code Online (Sandbox Code Playgroud)
我的问题是这样的,但我要求Python语法.我使用的是Python 3.5.1
使用dict映射名称到函数.
call_dict = {
'foo': foo,
'bar': bar
}
call_dict[callfunction]()
Run Code Online (Sandbox Code Playgroud)
在 Python 中使用命令模式是很常见的。首先将所有函数移到一个类中,并为它们指定具有输入中未使用的前缀的名称。然后使用getattr()找到正确的函数并调用它。
class Commands():
def cmd_foo(self):
print("Foo")
def callFunction(self, name):
fn = getattr(self, 'cmd_'+name, None)
if fn is not None:
fn()
Run Code Online (Sandbox Code Playgroud)
与 Daniel 的 call_dict 相比,这有几个优点:您不必再次列出函数的名称,也不必再次列出可调用的函数。
前缀'cmd_'的作用是确保您可以在类中拥有其他方法,但仍然可以准确控制哪些方法可以直接调用。
你可以这样做 :
eval(input("What function do you want to call? ") + '()')
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5776 次 |
| 最近记录: |