要重载哪些运算符才能使 Python 设置为正常运行



我正在编写一个简单的容器类,我想将其实例存储在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,

set 对象是不同可哈希对象的无序集合。

根据 https://docs.python.org/2.7/glossary.html#term-hashable,

如果对象具有在其生存期内永远不会更改的哈希值(它需要 __hash__() 方法),并且可以与其他对象进行比较(它需要 __eq__()__cmp__() 方法),则该对象是可哈希的。

你有__eq__,所以你现在需要的只是__hash__。(__ne__也应该实现,否则你会得到x == ynot (x != y)不匹配的结果。

class Point(object):
    def __init__(self, x, y):
        self.x = x
        self.y = y
    def __eq__(self, other):
        if isinstance(other, Point):
            return self.x == other.x and self.y == other.y
        return NotImplemented
    def __ne__(self, other)
        if isinstance(other, Point):
            return not (self == other)
        return NotImplemented
    def __hash__(self):
        return hash((self.x, self.y))

print(set([Point(1,2), Point(1,2)]))

结果:

set([<__main__.Point object at 0x02F4F090>])

对于样式点,您可能还希望实现 __repr__ ,以便您的 set 对象看起来不错。添加def __repr__(self): return "Point({}, {})".format(self.x, self.y),您的集将显示为 set([Point(1, 2)])

最新更新