我想知道我怎麼會去這樣做這樣的事情(在Python 2):如何用另一個函數調用具有任意參數的函數?
def myFunction(fn, params):
return ("You called " + fn.__name__ + "(" + str(params) ")" +
" and got " + str(fn(params)))
說我有一對夫婦的功能:
def doSomething(s):
# manipulation
return s
def doAnotherThing(someInt, someOtherInt, someString):
# do something with them
return someValue
我想成爲能夠撥打myFunction(doSomething, "hello")
,並獲得You called doSomething("hello") and got "something"
。這種方法似乎適用於採用單一輸入的函數,但我無法讓它適用於需要多個輸入的函數,例如調用myFunction(doAnotherThing, (myInt, myOtherInt, myString))
。我想我需要做一些涉及*
和**
的事情,以便我可以任意使用關鍵字而不是tuple
,但我不太確定如何去做。
你正在尋找一個[裝飾](http://simeonfranklin.com/blog/2012/jul/1/ python-decorators-in-12-steps /),我建議讀一下他們做你想做的事情。 – Jack 2014-09-22 18:30:09