我正在尝试修改第三方 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/