首页 > 解决方案 > Python:如何禁用在属性字典中创建新键?

问题描述

这是属性dict的简单代码:

class AttrDict(dict):
    def __init__(self, *args, **kwargs):
        super(AttrDict, self).__init__(*args, **kwargs)
        self.__dict__ = self

更多上下文: https ://stackoverflow.com/a/14620633/1179925

我可以像这样使用它:

d = AttrDict({'a':1, 'b':2})
print(d)

我希望这是可能的:

d.b = 10
print(d)

但我希望这是不可能的:

d.c = 4
print(d)

是否有可能在创建新密钥时引发错误?

标签: pythondictionaryattributes

解决方案


你可以检查他们是否已经在那里

class AttrDict(dict):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.__dict__ = self

    def __setattr__(self, key, value):
        if key not in [*self.keys(), '__dict__']:
            raise KeyError('No new keys allowed')
        else:
            super().__setattr__(key, value)

    def __setitem__(self, key, value):
        if key not in self:
            raise KeyError('No new keys allowed')
        else:
            super().__setitem__(key, value)

首先,我认为这是一个坏主意,因为不能添加初始值,但是从内置函数中它指出以下内容: dict(iterable) -> new dictionary initialized as if via: d = {} for k, v in iterable: d [k] = v

因此,这确实允许您更改方法而不影响 Class 的初始化,因为它从 {} 而不是从它自己的实例创建一个新方法。

不过,他们将能够始终更改 __ dict __ ..


推荐阅读