2010-12-07 14 views
5

對象的所有方法我想調用一個python對象實例的所有方法與給定的參數,即對於像的Python:調用與一組給定的參數

class Test(): 
    def a(input): 
     print "a: " + input 
    def b(input): 
     print "b: " + input 
    def c(input): 
     print "c: " + input 

我的目標想寫一個動態方法允許我跑

myMethod('test') 

導致

a: test 
b: test 
c: test 

通過遍歷所有測試() - 米編制方法。在此先感謝您的幫助!

回答

10

也不清楚爲什麼要這麼做。通常在unittest這樣的東西中,你會在你的類中提供一個輸入,然後在每個測試方法中引用它。

使用檢查和目錄。

from inspect import ismethod 

def call_all(obj, *args, **kwargs): 
    for name in dir(obj): 
     attribute = getattr(obj, name) 
     if ismethod(attribute): 
      attribute(*args, **kwargs) 

class Test(): 
    def a(self, input): 
     print "a: " + input 
    def b(self, input): 
     print "b: " + input 
    def c(self, input): 
     print "c: " + input 

call_all(Test(), 'my input') 

輸出:

a: my input 
b: my input 
c: my input 
+0

完美,謝謝。我將使用這種模式進行規則評估任務,而不是單元測試或文檔測試。 – sam 2010-12-07 08:41:50

1

你真的不想這樣做。 Python附帶兩個非常好的測試框架:請參閱文檔中的unittestdoctest模塊。

但你可以嘗試這樣的:

def call_everything_in(an_object, *args, **kwargs): 
    for item in an_object.__dict__: 
     to_call = getattr(an_object, item) 
     if callable(to_call): to_call(*args, **kwargs) 
相關問題