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