我很想在Python中使用一次写入字典对象,以便:
my_dict[1] = 'foo' my_dict[2] = 'bar' my_dict[1] = 'baz' # Raises KeyError我可以想象制作一个简单的,但我想知道是否存在一个更好的思路? 我找不到一个。
I'd quite like to have a write-once dictionary object in Python, so that:
my_dict[1] = 'foo' my_dict[2] = 'bar' my_dict[1] = 'baz' # Raises KeyErrorI can imagine making a straightforward one, but I wonder if a better-thought-out recipe exists? I couldn't find one.
最满意答案
实现一个子类很容易:
class WriteOnceDict(dict): def __setitem__(self, key, value): if key in self: raise KeyError('{} has already been set'.format(key)) super(WriteOnceDict, self).__setitem__(key, value)你也可以提供一个自定义的update()方法,根据你想要的严格程度, __delitem__() popitem() __delitem__() , pop() , popitem()和clear()也可能需要重写。
对于超严格版本,在collections.MutableMapping()混合会更容易,因为它通过__getitem__ , __setitem__和__delitem__调用为您实现大多数方法:
from collections import MutableMapping class StrictWriteOnceDict(MutableMapping, dict): # dict implementations to override the MutableMapping versions __getitem__ = dict.__getitem__ __iter__ = dict.__iter__ def __delitem__(self, key): raise KeyError('Read-only dictionary') def __setitem__(self, key, value): if key in self: raise KeyError('{} has already been set'.format(key)) dict.__setitem__(self, key, value)允许删除与使用__delitem__ = dict.__delitem__替换__delitem__方法一样简单。
It's easy enough to implement a subclass:
class WriteOnceDict(dict): def __setitem__(self, key, value): if key in self: raise KeyError('{} has already been set'.format(key)) super(WriteOnceDict, self).__setitem__(key, value)You could also provide a custom update() method, and depending on how strict you want to be, __delitem__(), pop(), popitem(), and clear() may need overriding too.
For the super-strict version, it's easier to mix in collections.MutableMapping() as it implements most methods for you in terms of __getitem__, __setitem__ and __delitem__ calls:
from collections import MutableMapping class StrictWriteOnceDict(MutableMapping, dict): # dict implementations to override the MutableMapping versions __getitem__ = dict.__getitem__ __iter__ = dict.__iter__ def __delitem__(self, key): raise KeyError('Read-only dictionary') def __setitem__(self, key, value): if key in self: raise KeyError('{} has already been set'.format(key)) dict.__setitem__(self, key, value)Allowing deletion is as simple as replacing the __delitem__ method with __delitem__ = dict.__delitem__.
更多推荐
发布评论