2009-04-23 48 views
0

我想寫一點代碼來調用給定參數指定的函數。 EG:實現'函數調用函數'

def caller(func): 
    return func() 

不過我還要做的是指定的可選參數「主叫方」功能,使「來電顯示」呼叫「功能」與指定的參數(如果有的話)。

def caller(func, args): 
# calls func with the arguments specified in args 

有沒有簡單的pythonic方法來做到這一點?

+0

這是scarily元。你確定你沒有過度泛化嗎? – 2009-04-23 16:53:35

回答

12

您可以通過使用arbitrary argument listsunpacking argument lists來完成此操作。

>>> def caller(func, *args, **kwargs): 
...  return func(*args, **kwargs) 
... 
>>> def hello(a, b, c): 
...  print a, b, c 
... 
>>> caller(hello, 1, b=5, c=7) 
1 5 7 

不知道爲什麼覺得有必要去做,雖然。

7

這已經作爲apply函數存在,儘管由於新的* args和** kwargs語法而被認爲是過時的。

>>> def foo(a,b,c): print a,b,c 
>>> apply(foo, (1,2,3)) 
1 2 3 
>>> apply(foo, (1,2), {'c':3}) # also accepts keyword args 

但是,*和**語法通常是更好的解決方案。以上相當於:

>>> foo(*(1,2), **{'c':3})