2017-04-27 50 views
0

如果我有存储在一个字符串,像这样一个函数的名称:将字符串转换

富=“some_function”假设我可以打电话给bar.some_function.baz(),我如何使用foo来做到这一点?很明显,这个例子并不能解释为什么我不能仅仅使用some_function,但是在实际的代码中,我迭代了一个我想调用的函数名称列表。

为了使它更清晰,如果bar.some_function.baz()打印'Hello world!'然后一些代码,使用foo但不是some_function应该这样做。是否有可能使用字符串的值和exec()

在此先感谢

+1

你的意思是你想*动态查找属性*?为此使用'getattr()'。 –

+0

你的情况:'getattr(bar,foo).baz()'。 –

+0

哦..有道理,谢谢。我不确定getattr()是这样工作的。谢谢。 (对不起,重复) –

回答

0

如果它是在一个类中,你可以使用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()