2016-06-08 74 views
1

有沒有辦法在Python中的循環內使用方法?像下面這樣:有沒有辦法在python的for循環中動態使用方法?

obj=SomePythonObject() 
list_of_methods=dir(obj) 
for i in list_of_methods: 
    try: 
     print obj.i()  
    except: 
     print i,'failed' 
+0

的[?我該怎麼辦可變的變量在Python(可能的複製http://stackoverflow.com/ questions/1373164/how-do-i-do-variable-variables-in-python)特別是第二個答案。 –

+1

這似乎有潛在的危險...更好的希望SomePythonObject沒有deleteUsersHardDrive方法。 – Kevin

+0

我明白了 - 只是嘗試一種新的Python API,它沒有很好的文檔,並且無法手動嘗試所有的方法。感謝您指出,雖然 – CiaranWelsh

回答

2

是的,這是可能的,使用callablegetattr

obj=SomePythonObject() 
list_of_methods=dir(obj) 
for i in list_of_methods: 
    try: 
     item = getattr(obj, i, None) 
     if callable(item): 
      item()  
    except: 
     print i,'failed' 
+0

「item = getattr(obj,im item)」im item? – lonewaft

+0

@lonewaft謝謝。固定 –

相關問題