[英]Custom Dictionary and JSON Module in Python
我有一个自定义Python类,用于扩展“ dict”内置类型。
########################################################################
class ServiceParametersNew(dict):
""""""
_allowed = ['maxRecordCount', 'tables',
'allowGeometryUpdates', 'supportsDisconnectedEditing',
'description', 'name', 'xssPreventionInfo',
'hasStaticData', 'capabilities', 'copyrightText',
'currentVersion', 'size', 'hasVersionedData',
'units', 'syncEnabled', 'supportedQueryFormats',
'editorTrackingInfo', 'serviceDescription']
_editorTrackingInfo = {
"enableEditorTracking": True,
"enableOwnershipAccessControl": False,
"allowOthersToUpdate": True,
"allowOthersToDelete": True}
_xssPreventionInfo = {
"xssPreventionEnabled": True,
"xssPreventionRule": "InputOnly",
"xssInputRule": "rejectInvalid"}
_tables = []
#----------------------------------------------------------------------
def __str__(self):
"""returns object as string"""
val = {}
for a in self._allowed:
if a in self.__dict__:
val[a] = self.__getitem__(a)
val['table'] = self._tables
val['xssPreventionInfo'] = self._xssPreventionInfo
val['editorTrackingInfo'] = self._editorTrackingInfo
return json.dumps(val)
#----------------------------------------------------------------------
def __getitem__(self, key):
if key.lower() in [a.lower() for a in self._allowed]:
return self.__dict__[key]
raise Exception("Invalid parameter requested")
#----------------------------------------------------------------------
def __setitem__(self, index, value):
self.__dict__[index] = value
#----------------------------------------------------------------------
@property
def xssPreventionInfo(self):
"""gets the xssPreventionInfo"""
return self._xssPreventionInfo
#----------------------------------------------------------------------
@property
def editorTrackingInfo(self):
"""gets the editorTrackingInfo settings"""
return self._editorTrackingInfo
#----------------------------------------------------------------------
def updateXssPreventionInfo(self, xssPreventionEnabled=True,
xssPreventionRule="InputOnly",
xssInputRule="rejectInvalid"):
"""updates the xss prevention information"""
self._xssPreventionInfo = {
"xssPreventionEnabled": True,
"xssPreventionRule": "InputOnly",
"xssInputRule": "rejectInvalid"
}
#----------------------------------------------------------------------
def updateEditorTrackingInfo(self,
enableEditorTracking=True,
enableOwnershipAccessControl=False,
allowOthersToUpdate=True,
allowOthersToDelete=True
):
"""updates the editor tracking information"""
self._editorTrackingInfo = {
"enableEditorTracking": enableEditorTracking,
"enableOwnershipAccessControl": enableOwnershipAccessControl,
"allowOthersToUpdate": allowOthersToUpdate,
"allowOthersToDelete": allowOthersToDelete
}
该类基本上将检查一个值是否在允许的字典中(如果存在),将其输入到该值中。
自从dict继承以来,我就可以使用json.dumps(<object>)
将类转储为字符串值。
我是否必须重写另一个功能才能使其正常工作?
您误解了__dict__
它不是存放dict
数据的地方,而是存放大多数类的属性的地方。 例如:
>>> class A(dict):
... def __init__(self):
... dict.__init__(self)
... self.x = 123
...
>>> a=A()
>>> a.__dict__
{'x': 123}
因此, a.__dict__['x']
通常(但不总是)与ax
相同。
作为一般规则: 除非您确实喜欢深色的禁忌魔法师,否则请勿使用__dict__ 。
为了使您的类正常工作并愉快地序列化为json,只需将dict.__getitem__
用作任何普通的超类方法调用即可。
class ExtendedDict(dict):
_allowed = ['a', 'b']
def __getitem__(self, key):
if key.lower() in [a.lower() for a in self._allowed]:
# Just call superclass method
return dict.__getitem__(self, key)
raise Exception("Invalid parameter requested")
d = ExtendedDict()
d['a'] = 1
d['b'] = 2
import json, sys
sys.stdout.write(json.dumps(d))
这将打印:
{"a": 1, "b": 2}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.