Python中有一种魔术设置方法吗?

时间:2020-11-06 12:59:13

标签: python python-3.x

我有一个这样的自定义对象:

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

我希望它根据以下规则使用集合:如果对象具有相同的x,则它们相等

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.

有没有一种我可以在MyObject中实现的魔术方法?

1 个答案:

答案 0 :(得分:6)

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

有关更多信息,请参见https://hynek.me/articles/hashes-and-equality/

相关问题