Last active
January 2, 2018 05:50
-
-
Save perrie625/9c5cf0a289d8fb8685c03616215cab09 to your computer and use it in GitHub Desktop.
python不可变字典
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ImmutableDict(dict): | |
_HASH = None | |
def __new__(cls, *args, **kwargs): | |
ImmutableDict._HASH = hash(frozenset(args[0].items())) | |
return super(ImmutableDict, cls).__new__(cls, args) | |
def __hash__(self): | |
return self._HASH | |
def _readonly(self, *args, **kwards): | |
raise TypeError("Cannot modify Immutable Instance") | |
__delattr__ = __setattr__ = __setitem__ = pop = update = setdefault = clear = popitem = _readonly |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment