我创建了一个类,它允许我使用任意字典键存储元数据,并且仍然通过in
原始对象类型的测试:
class DictKey:
def __init__(self, key):
self.hashkey = hash(key)
self.member = key
def __hash__(self):
return self.hashkey
def __repr__(self):
return 'DictKey(' + self.strkey + ')'
def __cmp__(self, o):
return cmp(self.member, o)
d = {}
key = DictKey('hello')
d[key] = 'world'
print key.hashkey
print hash('hello')
print key in d
print 'hello' in d
print DictKey('hello') in d
产生输出:
840651671246116861
840651671246116861
True
True
True
现在,给定字符串“hello”,我需要在恒定时间内获取从所述字符串创建的 DictKey 实例:
if 'hello' in d:
#need some way to return the instance of DictKey so I can get at it's member
tmp = d.getkey('hello')
tmp.member