在Dictionary中将对象添加为键

时间:2017-05-19 01:07:25

标签: python dictionary

我使用一个对象作为键,数字作为值但是在行中得到以下错误。有什么帮助吗?

  

dict [a] = 1

Traceback (most recent call last):
  File "detect_hung_connections.py", line 24, in <module>
    dict = {a:1}
TypeError: __hash__() takes exactly 3 arguments (1 given)

我的代码如下:

class A:
    def __init__(self,a,b):
        self.a = a
        self.b = b

    def __hash__(self,a,b):
        return hash(self.a,self.b)

    def __eq__(self,other):
        return (self.a,self.b) == (other.a,other.b)

dict ={}
a =  A("aa","bb")

dict[a] = 1

b = A("aa","bb")

2 个答案:

答案 0 :(得分:4)

A.__hash__的签名不应该采取任何额外的论点。

def __hash__(self):
    return hash((self.a,self.b))

答案 1 :(得分:1)

您正在使用整个对象调用哈希,并(冗余地)调用其两个属性。您只能使用一个值进行哈希处理。试试这个,也许吧:

def __hash__(self):
    return hash(self.a + self.b)

这至少会通过执行。