Does a Python object which doesn't override comparison operators equals itself?

后端 未结 3 474
独厮守ぢ
独厮守ぢ 2020-12-30 06:21
class A(object):

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

x = A(1)
y = A(2)

q = [x, y]
q.remove(y)

I want to remove from the li

3条回答
  •  [愿得一人]
    2020-12-30 07:07

    Yes. In your example q.remove(y) would remove the first occurrence of an object which compares equal with y. However, the way the class A is defined, you shouldn't ever have a variable compare equal with y - with the exception of any other names which are also bound to the same y instance.

    The relevant section of the docs is here:

    If no __cmp__(), __eq__() or __ne__() operation is defined, class instances are compared by object identity ("address").

    So comparison for A instances is by identity (implemented as memory address in CPython). No other object can have an identity equal to id(y) within y's lifetime, i.e. for as long as you hold a reference to y (which you must, if you're going to remove it from a list!)

    Technically, it is still possible to have objects at other memory locations which are comparing equal - mock.ANY is one such example. But these objects need to override their comparison operators to force the result.

提交回复
热议问题