代码点读机 / Python / __eq__

__eq__ Python · 特殊方法

定义两个对象用 == 比较时是否相等。

怎么用

def __eq__(self, 其他):

小例子

class 点:
    def __init__(self, x):
        self.x = x
    def __eq__(self, other):
        return self.x == other.x
print(点(1) == 点(1))

运行结果

True

官方文档:https://docs.python.org/zh-cn/3/reference/datamodel.html#object.__eq__

在代码里遇到不认识的词?打开代码点读机,点一下就懂 → ← Python全部词条