【发布时间】:2019-01-18 19:57:40
【问题描述】:
我正在编写一个简单的容器类,我想将其实例存储在set 中,并希望删除重复项。比如我可以用tuple作为容器来写:
in> set([(1,2),(1,2)])
out> {(1,2)}
但如果我改为定义
class Point(object):
def __init__(self, x, y):
self.x = x
self.y = y
def __ge__(self, other):
if self.x > other.x:
return True
elif self.x == other.x:
return self.y >= other.y
else:
return False
def __le__(self, other):
if self.x < other.x:
return True
elif self.x == other.x:
return self.y <= other.y
else:
return False
def __eq__(self, other):
return self.x == other.x and self.y == other.y
然后尝试
set([Point(1,2), Point(1,2)])
我最终得到了一组 2 个对象而不是 1 个。我需要重载哪些运算符(或者还需要做什么)才能使 set 以可预测的方式运行?
谢谢。
【问题讨论】:
-
set和dict对象依赖于对象的__hash__和__eq__方法。您正在继承默认散列,它本质上是按 identity 散列的。由于您的两个对象都是不同的,因此它们散列到单独的存储桶中。您希望您的__hash__和__eq__保持一致。在这种情况下,它们不是。
标签: python python-2.7 set operator-overloading