2014-02-13 20 views
0

在JavaScript中,我有多個具有名爲「one」的函數的不同模塊(對象)。現在在任何模塊/對象上調用某個函數

test_module1 = { 
    one: function() { 
     alert('fun mod1_one successful'); 
    }, 
    two: function() { 
     alert('fun mod1_two successful'); 
    } 
} 
test_module2 = { 
    one: function() { 
     alert('fun mod2_one successful'); 
    }, 
    two: function() { 
     alert('fun mod2_two successful'); 
    } 
} 

workingObj = test_module1; 
workingObj["one"](); 

,如果我有這些模塊中的一個/在變量「workingObj」對象和我想調用 函數「一」在此對象上,我請workingObj [「一」](); 。

目前我學習Python。這種語言是否有類似的東西?

我需要一個沒有Python類/繼承的解決方案。

非常感謝提前

沃爾夫岡

+0

你不使用'workingObj.one()'有什麼特別的原因嗎?你不知道你會提前打電話給哪個方法嗎? – user2357112

+0

你好user2357112!在某些情況下,我知道函數的名稱,在其他我不知道。 –

回答

4

絕對!所有你需要做的就是採取的「getattr」的優勢,並執行以下

class MyObj(object): 
    def func_name(self): 
     print "IN FUNC!" 

my_obj = MyObj() 

# Notice the() invocation 
getattr(my_obj, "func_name")() # prints "IN FUNC!" 
+0

布萊恩你好! 「my_obj」在Python中看起來如何?謝謝 –

+0

啊對不起,你需要更多的上下文,我已經更新了相應的答案 – Bryan

+0

'getattr'可能會矯枉過正。最有可能的是,你所需要的只是'my_obj.func_name()'。 – user2357112

1

您可以使用oprerator.methodcaller

from operator import methodcaller 
call_one = methodcaller("one") 

現在你可以使用get_one擺脫任何對象one並調用它像這

call_one(obj) 

優勢getattr

除了它非常可讀和慣用的事實之外,與getattr不同,您不必爲每個對象調用methodcaller。創建一次,只要你想用盡可能多的對象,就可以使用它。

例如,

class MyClass1(object): # Python 2.x new style class 
    def one(self): 
     print "Welcome" 

class MyClass2(object): # Python 2.x new style class 
    def one(self): 
     print "Don't come here" 

from operator import methodcaller 
call_one = methodcaller("one") 

obj1, obj2 = MyClass1(), MyClass2() 
call_one(obj1) # Welcome 
call_one(obj2) # Don't come here 
+1

如果你打算使用'operator',爲什麼不'operator.methodcaller'? – user2357112

+0

@ user2357112謝謝你:)我不知道它存在。更新了我的答案。 :) – thefourtheye

相關問題