On Tue, Dec 22, 2020 at 5:20 AM David Mertz <me...@gnosis.cx> wrote: > > On Mon, Dec 21, 2020 at 5:56 PM Paul Bryan <pbr...@anode.ca> wrote: >> >> I'm interested in knowing when (id(x), x) would be preferable over (type(x), >> x). > > > Something along these lines: > > >>> class Point: > ... def __init__(self, x, y): > ... self.x = x > ... self.y = y > ... def __eq__(self, other): > ... return self.x == other.x and self.y == other.y > ... def __hash__(self): > ... return 0 # Could make something better > ... > ... > >>> p1, p2, p3 = Point(1, 1), Point(2, 2), Point(1, 1) > >>> p1 == p2 > False > >>> p1 == p3 > True > >>> {p1, p2, p3} > {<__main__.Point object at 0x7f61f66a2d00>, <__main__.Point object at > 0x7f61f66a2f10>} >
If equality is based on self.x and self.y, the easiest way to do the hash is the same way: def __hash__(self): return hash((self.x, self.y)) But the real question is: Why do points compare equal based on their locations, if you need them to be independently stored in a set? Logically, if they are equal, the set either contains that one thing or it doesn't. ChrisA _______________________________________________ Python-ideas mailing list -- python-ideas@python.org To unsubscribe send an email to python-ideas-le...@python.org https://mail.python.org/mailman3/lists/python-ideas.python.org/ Message archived at https://mail.python.org/archives/list/python-ideas@python.org/message/C4KACGF7XXACQYGC5F4ZQX4S6AOVV3PI/ Code of Conduct: http://python.org/psf/codeofconduct/