[英]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 .我希望它根据规则使用集合:如果对象具有相同的
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.
Is there a magic method I could implement in MyObject
to reach my purpose?是否有我可以在
MyObject
实现的魔法方法来达到我的目的?
__eq__(self, other)
__hash__(self)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.