Created
March 16, 2026 20:19
-
-
Save mahenzon/84d0d8d0d879a4c147f36e60214d9ecb to your computer and use it in GitHub Desktop.
Python set add same hash value item if no eq
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class A: | |
| def __init__(self, val): | |
| self.val = val | |
| def __hash__(self): | |
| return hash(self.val) | |
| def __str__(self): | |
| return str(self.val) | |
| def __repr__(self): | |
| return str(self) | |
| class B: | |
| def __init__(self, val): | |
| self.val = val | |
| def __hash__(self): | |
| return hash(self.val) | |
| def __eq__(self, other): # important! | |
| return isinstance(other, self.__class__) and self.val == other.val | |
| def __str__(self): | |
| return str(self.val) | |
| def __repr__(self): | |
| return str(self) | |
| a1 = A(42) | |
| a2 = A(42) | |
| print({a1, a2}) | |
| # {42, 42} | |
| b1 = B(52) | |
| b2 = B(52) | |
| print({b1, b2}) | |
| # {52} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment