将字符串中存储的字符串转换为函数(Python)

将字符串中存储的字符串转换为函数(Python),python,string,python-2.7,function,Python,String,Python 2.7,Function,如果我将函数名存储在如下字符串中: foo='some_函数' 假设我可以调用bar.some_function.baz(),那么如何使用foo来实现呢?显然,这个例子并没有解释为什么我不能只使用一些函数,但在实际代码中,我迭代了一系列我想调用的函数名 为了更清楚,如果bar.some_function.baz()打印“Hello world!”然后一些代码,使用foo,而不是一些函数,也应该这样做。是否可以使用字符串和exec()的值 提前感谢如果它在类中,您可以使用getattr: clas

如果我将函数名存储在如下字符串中:

foo='some_函数'

假设我可以调用bar.some_function.baz(),那么如何使用foo来实现呢?显然,这个例子并没有解释为什么我不能只使用一些函数,但在实际代码中,我迭代了一系列我想调用的函数名

为了更清楚,如果bar.some_function.baz()打印“Hello world!”然后一些代码,使用foo,而不是一些函数,也应该这样做。是否可以使用字符串和exec()的值


提前感谢

如果它在类中,您可以使用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))
方法() 或者如果它是一个函数:

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

您的意思是要动态查找属性?使用
getattr()
。在您的情况下:
getattr(bar,foo).baz()
.Oh。。有道理,谢谢。我不确定getattr()是否能像那样工作。谢谢(很抱歉重复)