我有一个用作参数容器的类:
class Parameters:
param1 = {'name': 'color', 'value': 'blue'}
param2 = {'name': 'distance', 'value': 'far, far away'}
.
.
.
我可以指定可以写入参数的值吗? 例如,颜色可以只是蓝色和红色,如果我这样做:
params.param1['value'] = 'green'
它应该失败。
在C ++中,我可以创建一个枚举并将其用作类型,我想在Python中也应该可以使用类似的功能。
答案 0 :(得分:1)
你可以继承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
答案 1 :(得分:1)
您可以使用描述符。描述符将是可通过 dot 表示法访问的类的属性。
from weakref import WeakKeyDictionary
class RestrictedColor:
"""A descriptor that restricts values"""
def __init__(self, default):
self.value = default
self.data = WeakKeyDictionary()
def __get__(self, instance, owner):
return self.data.get(instance, self.value)
def __set__(self, instance, value):
if value.lower() not in ('blue','red'):
raise ValueError(f'{value} is not allowed')
self.data[instance] = value
class Parameters:
color = RestrictedColor('blue')
用法:
>>> p = Parameters()
>>> p.color
'blue'
>>> p.color = 'orange'
Traceback (most recent call last):
File "<pyshell#17>", line 1, in <module>
p.color = 'orange'
File "foo.py", line 40, in __set__
raise ValueError(f'{value} is not allowed')
ValueError: orange is not allowed
>>> p.color = 'red'
>>> p.color
'red'
>>> getattr(p, 'color')
'red'
>>>
如果您需要参数实例可订阅:
class BenignDescriptor:
"""A descriptor that accepts anything"""
def __init__(self, default):
self.value = default
self.data = WeakKeyDictionary()
def __get__(self, instance, owner):
return self.data.get(instance, self.value)
def __set__(self, instance, value):
self.data[instance] = value
class Parameters:
color = RestrictedColor('blue')
distance = BenignDescriptor('far, far away')
def __getitem__(self, item):
return getattr(self, item)
def __setitem__(self, item, value):
return setattr(self, item, value)
用法
>>> p = Parameters()
>>> p['color']
'blue'
>>> p.distance
'far, far away'
>>> p['distance'] = 'close'
>>> p['distance']
'close'
>>>