我在想我们如何实现一个InsertOnlyDict
,它有一个属性,如果一个键已经存在,它就不能被设置为新值
实现它的一种方法是编写如下内容:
class InsertOnlyDict(dict):
def __setitem__(self, key, value):
if key in self:
raise ....
super(InsertOnlyDict, self).__setitem__(key, value)
上面的方法有一个问题,如果调用者使用dict.__setitem__(x, k, v)
,它仍然可以更新它
实现这一点的第二种方法是写
class InsertOnlyDict(object):
__slots__ = ('_internal',)
def __init__(self, *args, **kwargs):
self._internal = dict(*args, **kwargs):
def __setitem__(self, key, value):
if key in self._internal:
raise....
self._internal[key] = value
这种方法最令人担心的是,这种InsertOnlyDict
不再是dict
,因此可能会导致像isinstance(x, dict)
这样的检查失败
有什么办法绕过它吗?e、 使一个类不真正使用父类,而仍然通过isinstance(x, dict)
这样的检查
你觉得这些方法怎么样
目前没有回答
相关问题 更多 >
编程相关推荐