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

例如,我有一个 str 对象: menu = 'install'。我想从这个字符串运行安装方法。例如,当我调用 menu(some, arguments)时,它将调用 install(some, arguments)。有什么办法吗?

142118 次浏览

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()

You can use a dictionary too.

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