Python:从字符串名称调用函数 [英] Python: call a function from string name
本文介绍了Python:从字符串名称调用函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个 str 对象,例如:menu = 'install'
.我想从这个字符串运行安装方法.例如,当我调用 menu(some, arguments)
时,它会调用 install(some, arguments)
.有没有办法做到这一点?
I have a str object for example: menu = 'install'
. I want to run install method from this string. For example when I call menu(some, arguments)
it will call install(some, arguments)
. Is there any way to do that ?
推荐答案
如果是在一个类中,可以使用getattr:
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()
这篇关于Python:从字符串名称调用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文