一次写字典?(Write

编程入门 行业动态 更新时间:2024-10-26 13:35:46
一次写字典?(Write-once dictionary?)

我很想在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 KeyError

I 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__.

更多推荐

本文发布于:2023-08-05 14:50:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1434055.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字典   Write

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!