小编Ken*_* Ly的帖子

在Python中使用对象作为字典中的键 - 哈希函数

我试图使用一个对象作为Python中字典的键值.我遵循其他一些我们需要实现2个函数的帖子的建议:hasheq

有了这个,我期待以下工作,但事实并非如此.

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)

有人可以帮助启发我为什么这不起作用?

python dictionary key object

7
推荐指数
2
解决办法
1万
查看次数

标签 统计

dictionary ×1

key ×1

object ×1

python ×1