python - 为什么我可以重新分配 dict.update 但不能重新分配 dict.__setitem__

标签 python

我正在尝试修改第三方 dict 类以使其在某个点之后不可变。 对于大多数类,我可以分配方法槽来修改行为。 然而,这对于所有类中的所有方法似乎都是不可能的。特别是对于 dict,我可以重新分配 update,但不能重新分配 __setitem__

为什么?它们有何不同?

例如:

class Freezable(object):
    def _not_modifiable(self, *args, **kw):
        raise NotImplementedError()

    def freeze(self):
        """
        Disallow mutating methods from now on.
        """
        print "FREEZE"
        self.__setitem__ = self._not_modifiable
        self.update = self._not_modifiable
        # ... others
        return self

class MyDict(dict, Freezable):
    pass

d = MyDict()
d.freeze()
print d.__setitem__  # <bound method MyDict._not_modifiable of {}>

d[2] = 3         # no error  -- this is incorrect.

d.update({4:5})  # raise NotImplementedError

最佳答案

请注意,您可以定义 __setitem__,例如:

def __setitem__(self, key, value):
    if self.update is Freezable._not_modifiable:
        raise TypeError('{} has been frozen'.format(id(self)))
    dict.__setitem__(self, key, value)

(这个方法有点笨拙;还有其他选项。但即使 Python 直接调用类的 __setitem__ ,它也是使其工作的一种方法。)

关于python - 为什么我可以重新分配 dict.update 但不能重新分配 dict.__setitem__,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55348488/

相关文章:

python - 是否有 python 示例的 pyqt4 引用文档?

python - 如何使用ModelMultipleChoiceFilter?

python - 如何在Python中编码/解码这个文件?

python - python中的xml文件解析

python - 如何根据数组中的特征的大小来标记特征?

python - 提取括号之间的文本并为每个文本位创建行

javascript - php - webscraping - 单击 ajax 调用然后抓取页面(可以在 python 中完成)

Python自定义方法设置新变量更改旧变量

python - pyside + py2exe,应用程序随机崩溃,没有有意义的错误消息

Raspberry Pi Zero 上的 Python 非法指令