在Python中使用getattr调用一个函数

这个问题在这里已经有了答案:

  • 通过使用其名称(字符串)调用模块的功能10个答案

  • 没有看到你到目前为止尝试完成的事情,你很难看到你想要完成什么。

    但是,如果要调用的函数实际上是某个对象上的方法,则可以使用getattr:

    # somestring is a string, but could be any object
    somestring = "valentyn"
    
    # somestring.upper happens to be a method
    method = getattr(somestring, "upper")
    
    # ...which can be called in the usual manner
    print(method())
    

    如果你想调用本地定义的函数,你可以使用locals():

    def wow():
        return "spam"
    
    # locals() returns a dict of variables and functions that are locally defined
    print(locals()["wow"]())
    

    如果您事先知道您想要公开哪些函数,则可以考虑编写函数的代码:

    def foo():
        ...
    
    def bar():
        ...
    
    funcs = {"foo": foo, "bar": bar}
    
    funcs["foo"]()
    

    最后,如果您想要运行的代码实际上是像您所说的那样从客户端发送的,那么您唯一的选择是使用eval但是,这将比上述选项更安全。

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

    上一篇: Call a function using getattr in Python

    下一篇: Making a menu in Python