我试图使用一个对象作为Python中字典的键值.我遵循其他一些我们需要实现2个函数的帖子的建议:hash和eq
有了这个,我期待以下工作,但事实并非如此.
class Test:
def __init__(self, name):
self.name = name
def __hash__(self):
return hash(str(self.name))
def __eq__(self, other):
return str(self.name) == str(other,name)
def TestMethod():
test_Dict = {}
obj = Test('abc')
test_Dict[obj] = obj
print "%s" %(test_Dict[hash(str('abc'))].name) # expecting this to print "abc"
Run Code Online (Sandbox Code Playgroud)
但它给了我一个关键的错误信息:
KeyError: 1453079729188098211
Run Code Online (Sandbox Code Playgroud)
有人可以帮助启发我为什么这不起作用?