On Tue, Dec 22, 2020 at 5:20 AM David Mertz
On Mon, Dec 21, 2020 at 5:56 PM Paul Bryan
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