Python:将函数作为参数传递,并设置选项

Python:将函数作为参数传递,并设置选项,python,function,parameters,Python,Function,Parameters,在Python中,我需要在相同的输入参数上调用许多非常相似的函数。唯一的问题是,其中一些函数需要设置选项,而有些函数则不需要设置。 例如: import scipy.stats scipy.stats.mannwhitneyu(sampleA, sampleB) [...some actions...] scipy.stats.mstats.ks_twosamp(sampleA, sampleB, alternative='greater') [...same actions as above.

在Python中,我需要在相同的输入参数上调用许多非常相似的函数。唯一的问题是,其中一些函数需要设置选项,而有些函数则不需要设置。 例如:

import scipy.stats
scipy.stats.mannwhitneyu(sampleA, sampleB)
[...some actions...]
scipy.stats.mstats.ks_twosamp(sampleA, sampleB, alternative='greater')
[...same actions as above...]
scipy.stats.mstats.mannwhitneyu(sampleA, sampleB, use_continuity=True)
[...same actions as above...]
因此,我想将这些函数的名称作为更通用的函数
computeTestats
,以及
samreak
sampleB
的输入参数传递,但我不知道如何处理有时不得不使用的选项

def computeStats(functionName, sampleA, sampleB, options???):
   functionName(sampleA, sampleB)  #and options set when necessary
   ...some actions...
   return testStatistic
如何指定有时必须设置,有时不必设置的选项?

使用:

然后您就可以像这样使用
computeTestats()

computeStats(scipy.stats.mstats.ks_twosamp, sampleA, sampleB, alternative='greater')
尽管如此,我并不完全相信你需要这个。简单一点怎么样

def postprocessStats(testStatistic):
   ...some actions...
   return testStatistic

postprocessStats(scipy.stats.mstats.ks_twosamp(sampleA, sampleB, alternative='greater'))
?


我认为这更容易阅读,同时也更一般。

Ha!最后一个解决方案很酷!至于
**kwargs
,当我没有指定它时,我猜它只是
,我可以将它作为参数传递,没有副作用,对吗?@RickyRobinson:使用
**kwargs
时,不指定参数是可以的。你只需要得到一个空字典,一切都会按预期进行。请注意,在
**kwargs
(和
*args
)中,名称只是约定。重要的一点是
def postprocessStats(testStatistic):
   ...some actions...
   return testStatistic

postprocessStats(scipy.stats.mstats.ks_twosamp(sampleA, sampleB, alternative='greater'))