我正在编写一个简单的容器类,我希望将其实例存储在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
以可预测的方式运行,我需要重载哪些操作符(或者需要执行哪些操作)
谢谢你
根据https://docs.python.org/2.7/library/stdtypes.html#set-types-set-frozenset
根据https://docs.python.org/2.7/glossary.html#term-hashable
你有
__eq__
,所以你现在只需要__hash__
(__ne__
也应该实现,否则会得到x == y
与not (x != y)
不匹配的结果。)结果:
对于样式点,您可能还需要实现
__repr__
,这样您的set对象看起来就不错了。加上def __repr__(self): return "Point({}, {})".format(self.x, self.y)
,您的集合将显示为set([Point(1, 2)])
相关问题 更多 >
编程相关推荐