问题
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...]
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?
回答1:
Use **kwargs:
def computeStats(func, sampleA, sampleB, **kwargs):
func(sampleA, sampleB, **kwargs)
...some actions...
return testStatistic
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.
来源:https://stackoverflow.com/questions/15654390/python-pass-function-as-parameter-with-options-to-be-set