Call a function using getattr in Python

This question already has an answer here:

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

  • It's a bit hard to see what exactly you're trying to accomplish without seeing what you've tried so far.

    Nonetheless, if the function you want to call is actually a method on some object, you can use 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())
    

    If you want to call functions that are locally defined, you can use locals():

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

    If you know in advance which functions you want to expose, you could consider making a dict of functions:

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

    Finally, if the code you want to run is actually sent from the client like you say, your only option is to use eval - however, this will be even less secure than the options above.

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

    上一篇: 如何将类方法分配给类属性?

    下一篇: 在Python中使用getattr调用一个函数