Sunday, May 19, 2013

Python: override hash key

list, dict等object不能直接当hashkey用,但是python里的tuple是可以的,如果要override自己定义的类,添加两个函数
__hash__(self),
__eq__(self, other)
即可。
例如:
class myclass:
  def __init__(self, str1,int2,var3):
     self.var1 = str1
     self.var2 = int2
     self.var3 = var3
  def __hash__(self):
     return hash((self.var1,self.var2))
  def __eq__(self,other):
     return (self.var1,self.var2) == (other.var1,other.var2)  

还有一种方法是用现成module: colletions.namedtuple(),这里就不写了。
参考来源:
http://stackoverflow.com/questions/4901815/object-as-a-dictionary-key

No comments:

Post a Comment