python - 根据另一个参数的值设置函数参数
问题描述
如果标题含糊不清,我深表歉意。让我解释一下情况。
假设我想根据某个分布生成一些随机数,它可以是均匀的、正态的、泊松的、二项式的等。每个分布都有自己的参数/关键字参数来定义,例如,正态有均值和标准,泊松有 lambda,均匀有upper_bound 和lower_bound 等等。我如何定义这个函数的签名,它应该将分布类型作为一个字符串作为一个参数,并且根据它的值,该函数应该具有必需的(关键字)参数,也就是分布参数,如均值和标准差?
def generate(distribution, params):
"""
Args:
distribution (str): can take values 'uniform', 'normal', 'poisson', etc.
params (dict of str: float): based on the value of distribution, it should have the required parameters for the distribution
"""
if distribution == 'uniform':
result = uniform(params['lower'], params['upper'])
elif distribution == 'normal':
result = normal(params['mean'], params['std'])
elif distribution == 'poisson':
result = poisson(params['lambda'])
elif ...:
...
我能想到的一种选择是在签名中添加 **kwargs,我可以在其中直接插入关键字参数 mean、std、lambda 等。但这很混乱,并且没有反映给定分布的相关所需参数。我想知道 Pythonic 的方法是什么。
这只是一个例子,我的问题是,一般来说,当某些参数依赖于与函数相关的其他参数的值时,我应该如何编写函数签名。这可能不仅仅是关于 Python,它更像是一个通用的编程/语言不可知的问题。
我觉得现在应该有一个简单明了的解决方案。任何建议表示赞赏。
解决方案
您可以使用返回所需函数类型的函数。像这样:
import random
def generate(dist):
if dist == 'uniform':
def uniformDist(lower=0, upper=1):
return random.uniform(lower,upper)
return uniformDist
if dist == 'poisson':
def poissonDist(lmbda=1,):
return poisson(lmbda)
return poissonDist
print(generate('poisson')(lmbda=3))
print(generate('uniform')(lower=34, upper=78))
推荐阅读
- angular - 无法使我的标题响应表具有粘性
- mocha.js - 无法使用 mocha 和 mochawesome 同时查看文件和控制台输出中的测试输出
- javascript - 我想从文件中写入和读取以在不同的 html 中显示分数
- python - 在 fasta 数据集中搜索可变氨基酸基序
- jquery - JQuery Widget Factory - 初始化后绑定事件侦听器不起作用 -
- excel - 带反斜杠的 xpath 查询返回空
- backend - 如何创建没有分段名称的新分段报价?
- c++ - 如何将多个可变参数模板元组类组合成一个类?
- python - 在python中处理mongodb中的请求超时的最佳方法是什么
- google-apps-script - 消除 Ref# 参考不存在问题