本文介绍了如何在Python中将字典设为只读的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的课程:

I have a class like:

class A:
    def __init__(self):
        self.data = {}

,有时我想禁止修改 self.data 字段.

and at some moment I want to prohibit self.data fields modification.

我已阅读 PEP-416拒绝通知,其中有一个有很多方法可以做到这一点.所以我想找到它们.

I've read in PEP-416 rejection notice that there are a lot of ways to do it. So I'd like to find what they are.

我尝试过:

a = A()
a.data = types.MappingProxyType(a.data)

应该可以,但是首先,它是python3.3 +,其次,当我多次执行此禁止"操作时,我得到了这个信息:

That should work but first, its python3.3+ and second, when I do this "prohibition" multiple times I get this:

>>> a.data = types.MappingProxyType(a.data)
>>> a.data = types.MappingProxyType(a.data)
>>> a.data
mappingproxy(mappingproxy({}))

尽管最好多次获得 mappingproxy({})会更好,因为我要禁止"很多次.检查 isinstance(MappingProxyType)是一个选项,但是我认为可以存在其他选项.

though it would be much better to get just mappingproxy({}) as I am going to "prohibit" a lot of times. Check of isinstance(MappingProxyType) is an option, but I think that other options can exist.

谢谢

推荐答案

使用 collections.Mapping 例如

import collections

class DictWrapper(collections.Mapping):

    def __init__(self, data):
        self._data = data

    def __getitem__(self, key):
        return self._data[key]

    def __len__(self):
        return len(self._data)

    def __iter__(self):
        return iter(self._data)

这篇关于如何在Python中将字典设为只读的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 08:35