2013-06-29 50 views
0
class MyClass(object): 
    def fn(): 
     return 1 

for i in [method for method in dir(inspect) if callable(getattr(inspect, method))]: 
    print i(MyClass) // Error here 

錯誤:類型錯誤: '海峽' 對象不是可調用從模塊執行所有功能

如果我改變print語句:

print "%s(MyClass)" % i 

這只是打印:

+2

你的''我''是一個字符串。你已經有代碼在那裏你將該字符串「轉換」爲一個函數。 –

+0

@MarkusUnterwaditzer,我不明白。你的意思是'print'%s(MyClass)「%i'? – row248

回答

2

dir(module)返回在modu中定義的名稱(字符串)列表le,而不是實際的功能或價值。要獲得這些信息,請使用getattr,您已將其用於callable檢查。

for name in dir(your_module): 
    might_be_function = getattr(your_module, name) 
    if callable(might_be_function): 
     print might_be_function(your_parameters) 

當然,它可能仍然是功能並不適用於給定參數的情況下,所以你可能要檢查這個第一,或在try塊包裹英寸

0

您是否需要按照名稱來調用所有方法?

class C1: 
    def f1(self): 
     print('f1---') 
    def f2(self): 
    print('f2---') 

inspect = C1() 
for i in [method for method in dir(inspect) if callable(getattr(inspect, method))]: 
    getattr(inspect, i)()