1

I have a custom object like this:

class MyObject:
    def __init__(self, x, y):
        self.x = x
        self.y = y

I want it to work with sets according to the rule: if objects have the same x they are equal.

s = set()
s.add(MyObject(1, 2))

print(MyObject(1, 3) in s)  # It is False. I want it to be True, because `x = 1` for both.

Is there a magic method I could implement in MyObject to reach my purpose?

Fomalhaut
  • 8,590
  • 8
  • 51
  • 95
  • Does this answer your question? [Elegant ways to support equivalence ("equality") in Python classes](https://stackoverflow.com/questions/390250/elegant-ways-to-support-equivalence-equality-in-python-classes) – Christopher Peisert Nov 06 '20 at 13:04

1 Answers1

7
  • __eq__(self, other)
  • __hash__(self)

See https://hynek.me/articles/hashes-and-equality/ for more

balderman
  • 22,927
  • 7
  • 34
  • 52
  • Do I need both methods to be implemented or one of them? – Fomalhaut Nov 06 '20 at 13:05
  • both methods have to be implemented. (but you better read about it in order to understand why) – balderman Nov 06 '20 at 13:06
  • 1
    @Fomalhaut I think `__hash__` is for getting the [underlaying hash table slot](https://github.com/python/cpython/blob/master/Objects/setobject.c#L72) and `__eq__` for [comparing the entries](https://github.com/python/cpython/blob/master/Objects/setobject.c#L83) – Abdul Niyas P M Nov 06 '20 at 13:12