关于顺序的议定书

2024-04-26 21:52:53 发布

您现在位置:Python中文网/ 问答频道 /正文

这是如何在python级别实现的?你知道吗

我有一个对象在很大程度上假装是dict(现在回想起来,我应该只是子类dict,但我不想重构代码库,我也想知道这一点以供将来参考),它看起来有点像

class configThinger(object):
    _config = {}
    def __getitem__(self, key):
        return self._config[key]
    def __setitem__(self, key, value):
        self._config[key] = value

当我尝试以configThingerInstance['whatever']的形式访问它的元素时,它的工作方式与预期的完全一样,并且行为正确

但是像这样的电话

t = configThinger()
t.populate() # Internal method that fills it with some useful data
if 'DEBUG' in t:
    doStuff()

结果引发KeyError,原因可能是'in'协议对相关密钥执行了getitem()查找。我是否需要提出一些其他例外来说明它不存在? 我不想做这种事。你知道吗

try:
    t['DEBUG']
except KeyError:
    pass
else:
    doStuff()

还有,这在文档中的什么地方?你知道吗

我四处看看

http://docs.python.org/tutorial/datastructures.html

http://docs.python.org/library/stdtypes.html

但不幸的是,试图在谷歌上搜索特定于“in”一词的东西是愚蠢的:

编辑1:

通过一堆跟踪打印,我可以看到程序调用configThingerInstance。getitem(0)

然而

t = {'rawk': 1,
     'rawr': 2,
    }
t[0] # Raises KeyError
'thing' in t # returns False

Tags: keyindebugselfconfighttpdocsvalue
2条回答

要获得对in运算符(包含即成员身份检查)的最佳支持,请在configThinger类上实现__contains__特殊方法:

class configThinger(object):
    _config = {}
    def __getitem__(self, key):
        return self._config[key]
    def __setitem__(self, key, value):
        self._config[key] = value
    def __contains__(self, key):
        return key in self._config

文档是here(还解释了支持in操作符的其他较小的方法)。你知道吗

听起来你想让输入操作符过载?你知道吗

您可以通过定义方法__contains__http://docs.python.org/reference/datamodel.html#object.contains

相关问题 更多 >