2017-04-27 75 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()