小编典典

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

python

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


阅读 177

收藏
2020-12-20

共1个答案

小编典典

如果在课程中,则可以使用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()
2020-12-20