要重载哪些运算符才能使Python正常工作

2024-04-20 12:59:37 发布

您现在位置: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以可预测的方式运行,我需要重载哪些操作符(或者需要执行哪些操作)

谢谢你


Tags: 对象inselffalsetruereturnifdef
1条回答
网友
1楼 · 发布于 2024-04-20 12:59:37

根据https://docs.python.org/2.7/library/stdtypes.html#set-types-set-frozenset

A set object is an unordered collection of distinct hashable objects.

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

An object is hashable if it has a hash value which never changes during its lifetime (it needs a __hash__() method), and can be compared to other objects (it needs an __eq__() or __cmp__() method).

你有__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)])

相关问题 更多 >