Python:通过字符串名称调用函数
我有一个字符串对象,比如说:menu = 'install'
。我想通过这个字符串来运行一个叫做 install 的方法。比如当我调用 menu(some, arguments)
时,它应该能调用 install(some, arguments)
。有没有什么办法可以做到这一点呢?
3 个回答
40
为什么我们不能直接使用 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
76
你也可以使用字典。
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)
153
如果是在一个类里面,你可以使用 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()