gpt4 book ai didi

python - 指定 python 字典中可能的值

转载 作者:行者123 更新时间:2023-12-01 02:02:30 27 4
gpt4 key购买 nike

我有一个类用作参数容器:

class Parameters:
param1 = {'name': 'color', 'value': 'blue'}
param2 = {'name': 'distance', 'value': 'far, far away'}
.
.
.

我可以指定哪些值可以写入参数吗?例如颜色只能是蓝色和红色,如果我这样做:

params.param1['value'] = 'green'

它应该失败。

在 C++ 中,我可以创建一个枚举并将其用作类型,我想在 Python 中也应该可以实现类似的功能。

最佳答案

您可以子类 dict并在那里添加您的控件。然后定义param1 = ControlDict({...}) .

class ControlDict(dict):
def __init__(self, *args, **kwargs):
self.permitted_vals = {'onekey': {1, 2, 3},
'value': {'blue', 'red'}}

def update(self, *args, **kwargs):
other = dict(args[0])
for key in other:
if other[key] not in self.permitted_vals[key]:
raise ValueError("invalid value supplied for {0}".format(key))
self[key] = other[key]


d = ControlDict({})

d.update({'value': 'blue'})
# works

d.update({'value': 'green'})
# ValueError: invalid value supplied for value

关于python - 指定 python 字典中可能的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49454770/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com