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

后端 未结 3 475
独厮守ぢ
独厮守ぢ 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:22

    The answer is yes and no.

    Consider the following example

    >>> class A(object):
        def __init__(self, value):
            self.value = value        
    >>> x = A(1)
    >>> y = A(2)
    >>> z = A(3)
    >>> w = A(3)
    >>> q = [x, y,z]
    >>> id(y) #Second element in the list and y has the same reference
    46167248
    >>> id(q[1]) #Second element in the list and y has the same reference
    46167248
    >>> q.remove(y) #So it just compares the id and removes it
    >>> q
    [<__main__.A object at 0x02C19AB0>, <__main__.A object at 0x02C19B50>]
    >>> q.remove(w) #Fails because though z and w contain the same value yet they are different object
    Traceback (most recent call last):
      File "", line 1, in 
        q.remove(w)
    ValueError: list.remove(x): x not in list 
    

    It will remove from the list iff they are the same object. If they are different object with same value it won;t remove it.

提交回复
热议问题