我有一个str对象,例如:menu = 'install'。我想从此字符串运行安装方法。例如,当我打电话menu(some, arguments)时它将呼叫install(some, arguments)。有什么办法吗?
menu = 'install'
menu(some, arguments)
install(some, arguments)
如果在课程中,则可以使用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()