Comparing two identical objects in Python (2.7) returns False

前端 未结 1 1303
误落风尘
误落风尘 2021-01-26 03:40

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 li

相关标签:
1条回答
  • 2021-01-26 03:48

    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
    
    0 讨论(0)
提交回复
热议问题