用不可变键定义一个蟒蛇字典,但可变值 [英] Define a python dictionary with immutable keys but mutable values

查看:106
本文介绍了用不可变键定义一个蟒蛇字典,但可变值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗯,问题在标题中:我如何使用不可变键定义一个python字典,但是可变值?我想出了这个(在python 2.x中):

  class FixedDict(dict):

具有固定键的字典


def __init __(self,dictionary):
dict .__ init __(self)
for key in dictionary.keys():
dict .__ setitem __(self,key,dictionary [key])

def __setitem __(self,key,item):
如果键不在自我中:
raise KeyError(键+键+'未定义)
dict .__ setitem __(self,key,item)
/ pre>

但它看起来像我(不出意料的)相当马虎。特别是,这是安全的还是有实际改变/添加一些密钥的风险,因为我是继承自?
谢谢。

解决方案

考虑代理 dict 而不是子类化它。这意味着只有您定义的方法将被允许,而不是退回到 dict 的实现。

  class FixedDict(object):
def __init __(self,dictionary):
self._dictionary = dictionary
def __setitem __(self,key,item) :
如果键不在self._dictionary:
raise KeyError(键{}未定义。format(key))
self._dictionary [key] = item
def __getitem __(self,key):
return self._dictionary [key]

此外,您应该使用字符串格式而不是 + 来生成错误消息,否则将为任何不是字符串的值崩溃。


Well, the question is in the title: how do I define a python dictionary with immutable keys but mutable values? I came up with this (in python 2.x):

class FixedDict(dict):
    """
    A dictionary with a fixed set of keys
    """

    def __init__(self, dictionary):
        dict.__init__(self)
        for key in dictionary.keys():
            dict.__setitem__(self, key, dictionary[key])

    def __setitem__(self, key, item):
        if key not in self:
            raise KeyError("The key '" +key+"' is not defined")
        dict.__setitem__(self, key, item)

but it looks to me (unsurprisingly) rather sloppy. In particular, is this safe or is there the risk of actually changing/adding some keys, since I'm inheriting from dict? Thanks.

解决方案

Consider proxying dict instead of subclassing it. That means that only the methods that you define will be allowed, instead of falling back to dict's implementations.

class FixedDict(object):
        def __init__(self, dictionary):
            self._dictionary = dictionary
        def __setitem__(self, key, item):
                if key not in self._dictionary:
                    raise KeyError("The key {} is not defined.".format(key))
                self._dictionary[key] = item
        def __getitem__(self, key):
            return self._dictionary[key]

Also, you should use string formatting instead of + to generate the error message, since otherwise it will crash for any value that's not a string.

这篇关于用不可变键定义一个蟒蛇字典,但可变值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆