簡體   English   中英

Python中的自定義詞典和JSON模塊

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM