Python:将函数作为参数传递,并设置选项 [英] Python: pass function as parameter, with options to be set

查看:67
本文介绍了Python:将函数作为参数传递,并设置选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In Python, I need to call many very similar functions on the same input arguments sampleA and sampleB . The only thing is that some of these functions require an option to be set, and some don't. For example:

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 ,但我不知道该如何处理有时需要使用的选项.

Therefore I would like to pass the names of such functions as input argument of a more generic function computeStats, as well as sampleA and sampleB, but I don't know how to handle options that I sometimes have to use.

def computeStats(functionName, sampleA, sampleB, options???):
   functionName(sampleA, sampleB)  #and options set when necessary
   ...some actions...
   return testStatistic

如何指定有时必须设置的选项,有时不需要设置?

How do I specify an option that sometimes has to be set, sometimes not?

推荐答案

使用然后您将可以像这样使用 computeStats():

Then you'll be able to use computeStats() like so:

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

也就是说,我并不完全相信您完全需要这个.简单地

That said, I am not entirely convinced you need this at all. How about simply

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

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

?

我认为这更容易阅读,同时更普遍.

I think this is easier to read and at the same time is more general.

这篇关于Python:将函数作为参数传递,并设置选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆