python 重载 __hash__ __eq__
__author__ = 'root' from urlparse import urlparse class host_news(): def __init__(self, id, url): self.id = id urlinfo = urlparse(url) self.host = urlinfo.hostname self.url = url def __init__(self, id, host, url): self.id = id self.host = host self.url = url def __eq__(self, other): return self.host == other.host def __hash__(self): return self.host.__hash__() def __str__(self): return 'id:%s host:%s url:%s' % (self.id, self.host, self.url) if __name__ == '__main__': o1 = host_news(0, 'www'*2, 'www.1') o2 = host_news(0, 'www'*2, '100') o3 = host_news(1, 'qqq'*2, '10000') print o1 is o2 print o1 == o2 t = [o1, o3] print o2 in t
# 注释掉__hash__ __eq__ 结果就全是false