Comparing two identical objects in Python (2.7) returns False

柔情痞子 提交于 2019-12-02 10:24:27

By default, two distinct instances of any user-defined class are unequal:

>>> class X: pass
... 
>>> a = X()
>>> b = X()
>>> a == b
False

If you want different behaviour, you have to define it:

class Y:

    def __init__(self, value):
        self.value = value

    def __eq__(self, other):
        return self.value == other.value
>>> c = Y(3)
>>> d = Y(3)
>>> e = Y(4)
>>> c == d
True
>>> d == e
False
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!