Python: call a function from string name

This question already has an answer here:

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

  • If it's in a class, you can use getattr:

    class MyClass(object):
        def install(self):
              print "In install"
    
    method_name = 'install' # set by the command line options
    my_cls = MyClass()
    
    method = None
    try:
        method = getattr(my_cls, method_name)
    except AttributeError:
        raise NotImplementedError("Class `{}` does not implement `{}`".format(my_cls.__class__.__name__, method_name))
    
    method()
    

    or if it's a function:

    def install():
           print "In install"
    
    method_name = 'install' # set by the command line options
    possibles = globals().copy()
    possibles.update(locals())
    method = possibles.get(method_name)
    if not method:
         raise NotImplementedError("Method %s not implemented" % method_name)
    method()
    

    你也可以使用字典。

    def install():
        print "In install"
    
    methods = {'install': install}
    
    method_name = 'install' # set by the command line options
    if method_name in methods:
        methods[method_name]() # + argument list of course
    else:
        raise Exception("Method %s not implemented" % method_name)
    

    Why cant we just use eval()?

    def install():
        print "In install"
    

    New method

    def installWithOptions(var1, var2):
        print "In install with options " + var1 + " " + var2
    

    And then you call the method as below

    method_name1 = 'install()'
    method_name2 = 'installWithOptions("a","b")'
    eval(method_name1)
    eval(method_name2)
    

    This gives the output as

    In install
    In install with options a b
    
    链接地址: http://www.djcxy.com/p/55158.html

    上一篇: 使用一个字符串在Python中调用函数

    下一篇: Python:从字符串名称中调用一个函数