Fomalhaut
Fomalhaut

Reputation: 9825

Is there a magic method for sets in Python?

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?

Upvotes: 1

Views: 660

Answers (1)

balderman
balderman

Reputation: 23825

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

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

Upvotes: 7

Related Questions