如何在一个python水平这个实施?

我已经得到了伪装成大部分的字典(回想起来我刚才应该字典子类的对象,但我宁愿不重构代码库,我也想知道这对未来参考),它看起来有点像

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

因为它应该工作哪些准确和正确的行为,当我试图访问它的元素configThingerInstance [“什么”]

但是,像

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

在一个KeyError异常结果被升高,因为据推测在`协议做了的的GetItem ()用于所讨论的键查找。我需要提出一些其他异常,告诉在它的不存在? 我宁愿不做这样的事情。

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

而且,当在文档中是什么?

我环顾四周

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

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

但可悲试图谷歌具体为“在”字的东西是愚蠢:(

EDIT 1:

使用微量打印的堆叠,我可以看到,程序调用configThingerInstance。的的GetItem (0)

然而

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

解决方案

这听起来像你想重载的操作?

可以做到这一点通过定义方法__contains__ HTTP://文档.python.org /参考/ datamodel.html#对象。的包含

其他提示

有关的in运营商提供最好的支持(又名遏制成员检查),实现你的__contains__configThinger特殊方法:

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

该文档被此处(也说明其他较小的方式,以支持in操作符)。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top