在 Python 中,我需要在相同的输入参数 sampleA
和 sampleB
上调用许多非常相似的函数。唯一的问题是,其中一些功能需要设置选项,而有些则不需要。
例如:
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...]
因此,我想将此类函数的名称传递为更通用函数 computeStats
的输入参数,以及 sampleA
和 sampleB
,但我不知道如何处理有时必须使用的选项。
def computeStats(functionName, sampleA, sampleB, options???):
functionName(sampleA, sampleB) #and options set when necessary
...some actions...
return testStatistic
我如何指定一个有时必须设置、有时不需要设置的选项?
最佳答案
使用**kwargs
:
def computeStats(func, sampleA, sampleB, **kwargs):
func(sampleA, sampleB, **kwargs)
...some actions...
return testStatistic
然后您就可以像这样使用computeStats()
:
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'))
?
我认为这更容易阅读,同时也更通用。
关于Python:将函数作为参数传递,并设置选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15654390/