Comparing two identical objects in Python (2.7) returns False

旧城冷巷雨未停 提交于 2019-12-02 15:16:23

问题


I have a function in Python called object_from_DB. The definition isn't important except that it takes an ID value as an argument, uses the sqlite3 library to pull matching values from a table in a .db file, and then uses those values as arguments in the initialization of an object. The database is in no way changed by the use of this function.

This sample code, in light of this, baffles me.

>>> x = object_from_DB(422)
>>> y = object_from_DB(422)
>>> x == y
False

Why does this happen, and what sort of technique will cause x and y to return True when compared?


回答1:


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


来源:https://stackoverflow.com/questions/37648137/comparing-two-identical-objects-in-python-2-7-returns-false

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!