2011-06-09 142 views
64

Python函數可以作爲另一個函數的參數嗎?作爲函數參數的Python函數?

說:

def myfunc(anotherfunc, extraArgs): 
    # run anotherfunc and also pass the values from extraArgs to it 
    pass 

所以這基本上是兩個問題:

  1. 是否允許呢?
  2. 如果是這樣,我該如何使用其他函數內部的函數?我需要使用exec(),eval()或類似的東西嗎?從不需要惹他們。

BTW,extraArgs是anotherfunc參數的列表/元組。

+0

相關:https://stackoverflow.com/questions/47502068/is-there-a-formal-name-for-a-function-that-accepts-a-functions-as-an-argument/47634215#47634215 – alseether 2017-12-04 15:09:42

回答

73

Python函數可以作爲另一個函數的參數 嗎?

是的。

def myfunc(anotherfunc, extraArgs): 
    anotherfunc(*extraArgs) 

更具體...各種參數...

>>> def x(a,b): 
...  print "param 1 %s param 2 %s"%(a,b) 
... 
>>> def y(z,t): 
...  z(*t) 
... 
>>> y(x,("hello","manuel")) 
param 1 hello param 2 manuel 
>>> 
+0

extraArgs可以作爲一個函數嗎?如果是的話,你怎麼稱呼它? – Sekai 2015-04-09 17:49:09

+0

@sekai是的,extraArgs也可以是一個函數。 – 2015-04-09 23:43:18

+0

它需要通過作爲y(z,* t) – sabujp 2015-09-18 00:21:23

2
  1. 是的,這是允許的。
  2. 您使用的功能,你會任何其他:在Python anotherfunc(*extraArgs)
15

函數是第一類對象。但是你的函數定義爲is a bit off

def myfunc(anotherfunc, extraArgs, extraKwArgs): 
    return anotherfunc(*extraArgs, **extraKwArgs) 
3

當然,這也就是爲什麼蟒蛇實現下列方法,其中第一個參數是一個函數:

  • 地圖(函數,迭代,...) - 應用功能的迭代 每一個項目並返回結果列表。
  • 過濾器(函數,可迭代的) - 從那些元素構造一個列表 可迭代的函數返回true。
  • reduce(函數,iterable [,初始值設定項]) - 將兩個參數的兩個參數累加到可迭代項左邊的 右邊,以便將迭代次數減少爲單個值。
  • lambdas
2
  1. 是。通過將函數調用包含在輸入參數/ s中,可以一次調用兩個(或更多)函數。

例如:

def anotherfunc(inputarg1, inputarg2): 
    pass 
def myfunc(func = anotherfunc): 
    print func 

當你調用MYFUNC,你這樣做:

myfunc(anotherfunc(inputarg1, inputarg2)) 

這將打印anotherfunc的返回值。

希望這會有所幫助!

19

上述所有例子導致TypeErrors除非你的函數調用其它功能高清使用*args(也可選),**kwargs

def a(x, y): 
    print x, y 

def b(other, function, *args, **kwargs): 
    function(*args, **kwargs) 
    print other 

b('world', a, 'hello', 'dude') 

輸出

hello dude 
world 

注意function*args,**kwargs必須按順序並且必須是調用該函數的函數的最後一個參數。

+0

更多信息* args&** kwargs可以在這裏找到https://pythontips.com/2013/08/04/args-and-kwargs-in-python-explained/ – 2018-02-16 00:40:13