0
我有一个类只需要kwargs
。该参数kwargs['content']
包含user
和theme
键:使用Python来映射键和数据类型在kwargs
> content = "{'user': 1, 'theme':'red'}"
> kwargs['content'] = content
> m = Message(**kwargs)
我需要一个灵活的方式来建模是什么kwargs['content']
和检查...
- 一些关键在kwargs [“内容”]总是当下。
- 始终确保值不为空并且与类型匹配。
这是我试过的,但我觉得有更好的办法。
class Message(object):
def __init__(self, *args, **kwargs):
for field in self._hash_model():
if field not in kwargs['content']:
raise ValidationError('Missing % field'.format(field))
# check type
# turn to json
def _hash_model(self):
"""
My model of values that need to be in content
"""
model = {
'user': int,
'theme': str
}
return model
我正在使用Python 3.4。
'__init__'方法也在使用'* args'? – AKS
'content'是一个'str'或者'dict'? –
@CPanda内容不幸传入字符串! – Prometheus