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

标签 python function parameters

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

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 的输入参数,以及 sampleAsampleB,但我不知道如何处理有时必须使用的选项。

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/

相关文章:

Python webapp 动态路径

python - 在列表中操作列表的优雅方法?

Python > 将字符串变量传递到方法中

c++ - [方括号]和*星号之间的区别

c++ - 调用使用字符数组的类函数 (C++)

c# - 将零参数作为参数传递——行为定义在哪里?

python - Django 将表迁移到新数据库

javascript - onclick换色器JS函数

bash - 将 bash 脚本参数传递给子进程不变

c++ - 将 "normal"参数转换为模板化参数是否正确?