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

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

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

  • 如果它在一个类中,则可以使用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()
    

    或者如果它是一个功能:

    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)
    

    为什么不能使用eval()?

    def install():
        print "In install"
    

    新方法

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

    然后你调用下面的方法

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

    这给出了输出

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

    上一篇: Python: call a function from string name

    下一篇: Static initializer in Python