如何在Python中将字典设为只读 [英] How to make dictionary read-only in Python

查看:94
本文介绍了如何在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.

谢谢

推荐答案

使用 查看全文

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