我试图使用一个对象作为 python 字典中的键,但它的行为方式我不太理解。
首先,我创建一个以我的对象为键的字典:
package_disseminators = {
ContentType("application", "zip", "http://other/property") : "one",
ContentType("application", "zip") : "two"
}
现在创建另一个与作为键的对象“相同”的对象。
content_type = ContentType("application", "zip", "http://other/property")
我已经给了 ContentType 对象自定义__eq__
和定制__str__
方法,使得__eq__
方法比较了__str__
values.
现在,一些交互式Python:
>>> for key in package_disseminators:
... if key == content_type:
... print "match"
... else:
... print "no match"
...
no match
match
>>> content_type in package_disseminators.keys()
True
好的,看起来我的对象肯定被正确识别为密钥,所以:
>>> package_disseminators[content_type]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: (& (type="application/zip") (packaging="http://other/property") )
呃……好吧?所以 content_type 在 package_disseminators.keys() 列表中,但不是键?
>>> package_disseminators.has_key(content_type)
False
显然不是。
我认为 Python 用于确定相等性的比较过程在列表上的直接“in”语句和实际在字典中查找键之间有所不同,但我不知道如何。有什么建议或见解吗?