我有一个这样的自定义对象:
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
中实现的魔术方法?
答案 0 :(得分:6)
__eq__(self, other)
__hash__(self)