我试图在python字典中使用一个对象作为键,但是它的行为方式让我无法完全理解。
首先,我创建一个以对象为键的字典:
package_disseminators = {
ContentType("application", "zip", "http://other/property") : "one",
ContentType("application", "zip") : "two"
}
现在创建另一个对象,该对象与一个键“相同”。
content_type = ContentType("application", "zip", "http://other/property")
我已经给了ContentType对象custom__eq__
和custom__str__
方法,以便__eq__
方法比较__str__
值。
现在,一些交互式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_displaminators.keys()列表中,但它不是一个键吗?
>>> package_disseminators.has_key(content_type)
False
显然不是。
我假设Python用于确定相等性的比较过程在列表上的直接“in”语句和实际在dict中查找键之间是不同的,但我不知道如何实现。有什么建议或见解吗?
从python文档中:
Hashable定义如下
因此,如果您想这样做,您需要重写对象上的默认
__hash__()
方法(请参阅下面史蒂文·伦巴尔斯基的注释以获得进一步的解释)。我想这是可行的,因为
dict.keys()
返回一个列表,并且__contains__
可能检查等式,但不检查相同的散列。由于dict是隐藏的哈希表,因此需要同时定义
__eq__
和__hash__
才能工作。基本经验法则是:
__eq__
比较相等的对象,__hash__
必须返回相同的哈希。从你的描述来看
应该有用。
相关问题 更多 >
编程相关推荐