本文介绍了如何在python中创建一个不可变的字典?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在python中子类 dict ,这样子类的所有字典都是不可变的。 / p>

我不明白 __ hash __ 如何影响不可变性,因为在我的理解中,它只是表示平等不相等的对象!



因此,可以 __ hash __ 用于实现不变性?如何?



更新



目标是,可用作dict,必须作为全局变量共享。

解决方案

找到官方参考资料:

  class imdict(dict):
def __hash __(self):
return id(self)

def _immutable (self,* args,** kws):
raise TypeError('object is immutable')

__setitem__ = _immutable
__delitem__ = _immutable
clear = _immutable
update = _immutable
setdefault = _immutable
pop = _immutable
popitem = _immutable


b $ b

归属:


I want to subclass dict in python such that all the dictionaries of the sub-class are immutable.

I don't understand how does __hash__ affects the immutability, since in my understanding it just signifies the equality or non-equality of objects !

So, can __hash__ be used to implement immutability ? How ?

Update:

Objective is that common response from an API is available as a dict, which has to be shared as a global variable. So, that needs to be intact no matter what ?

解决方案

Found an Official reference :

class imdict(dict):
def __hash__(self):
    return id(self)

def _immutable(self, *args, **kws):
    raise TypeError('object is immutable')

__setitem__ = _immutable
__delitem__ = _immutable
clear       = _immutable
update      = _immutable
setdefault  = _immutable
pop         = _immutable
popitem     = _immutable

Attribution : http://www.python.org/dev/peps/pep-0351/

这篇关于如何在python中创建一个不可变的字典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 08:10