Call a function from a stored string in Python

This question already has an answer here:

  • Calling a function of a module by using its name (a string) 10 answers

  • 你可以这样做 :

    eval(input("What function do you want to call? ") + '()')
    

    使用一个字典映射名称的功能。

    call_dict = {
        'foo': foo,
        'bar': bar
    }
    call_dict[callfunction]()
    

    It is quite common in Python to use the command pattern. First move all of your functions into a class, and give them names which have a prefix that isn't used in the input. Then use getattr() to find the correct function and call it.

    class Commands():
       def cmd_foo(self):
           print("Foo")
    
       def callFunction(self, name):
           fn = getattr(self, 'cmd_'+name, None)
           if fn is not None:
                fn()
    

    This has a couple of advantages over Daniel's call_dict: you don't have to list the name of the functions a second time, and you don't have to list the callable functions a second time either.

    The 'cmd_' prefix is there to ensure you can have other methods in the class but still control exactly which ones are directly callable.

    链接地址: http://www.djcxy.com/p/55168.html

    上一篇: 在Python中制作菜单

    下一篇: 从Python中存储的字符串调用函数