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

时间:2011-10-29 02:17:48

标签: python

我有一个str对象,例如:menu = 'install'。我想从这个字符串运行install方法。例如,当我致电menu(some, arguments)时,它会拨打install(some, arguments)。有没有办法做到这一点?

3 个答案:

答案 0 :(得分:103)

如果是在课堂上,你可以使用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()

答案 1 :(得分:54)

您也可以使用字典。

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)

答案 2 :(得分:35)

为什么我们不能使用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