python - 良好做法默认值

标签 python python-2.7 tuples default-value

我有几个运输品牌,我想为每个品牌指定所有可用的 模型以及默认模型。

所以我首先这样定义了元组:

SUZUKI = ('model_1', 'model_2', 'model_3')
FERRARI = ('model_1', 'model_2')
# etc

我想为每个品牌指定一个默认型号。问题是有这么多品牌, 为它们中的每一个定义一个默认变量会很乏味:

SUZUKI_DEFAULT = 'model_1'
FERRARI_DEFAULT = 'model_2'
# etc

等等。所以我想知道什么是解决这个问题的好而不是太破旧的解决方案。 为每个品牌创建一个类可能会浪费资源,因为我不需要更多 附加参数或函数。

我想到了做这样的事情,将默认值放在元组的末尾, 然后指定默认值的位置:

DEFAULT_POSITION = -1
SUZUKI = ('model_1', 'model_2', 'model_3', 'model_1')
FERRARI = ('model_1', 'model_2', 'default_model')
PORSCH = ('model_1', 'model_2', None)
# etc

然后我会做一个检查语句,例如:

if arg not in SUZUKI:
    arg = SUZUKI[DEFAULT_POSITION]

我的问题是,这是一种不好的做法吗,是否还有其他解决方案(如果不是更好的话)?

最佳答案

为什么不使用字典,在我看来是更好的方法。代码本身将变得更容易理解和更容易。

brands = {'Suzuki':['model_1', 'model_2'], 'Ferrari':['model_1', 'model_2']}

然后正常调用它们:

brands['Suzuki']

输出:

['model_1', 'model_2']

关于python - 良好做法默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34948779/

相关文章:

python - 在 python 中向 unix 时间戳添加小时数

go - 在 Go 中使用 int 和 str 数组

scala - 为什么在 Scala 中使用元组而不是 Set?

python - Python 中的元组声明

python - 使用 RE 从可能的搜索结果集中选择最小的

python-2.7 - imshow 一个灰度图像和一个二进制图像 python

python - if 语句未到达

java - 如何在java中初始化变量时返回对象?

python - 在 Pandas 的 groupby 对象中绘制每个组的大小

python - 前瞻内组内的反向引用