In Python, is object() equal to anything besides itself?

后端 未结 2 1902
天涯浪人
天涯浪人 2021-01-01 14:00

If I have the code my_object = object() in Python, will my_object be equal to anything except for itself?

I suspect the answer lies in the

2条回答
  •  死守一世寂寞
    2021-01-01 14:48

    object doesn't implement __eq__, so falls back on the default comparison id(x) == id(y), i.e. are they the same object instance (x is y)?

    As a new instance is created every time you call object(), my_object will never* compare equal to anything except itself.

    This applies to both 2.x and 3.x:

    # 3.4.0
    >>> object().__eq__(object())
    NotImplemented
    
    # 2.7.6
    >>> object().__eq__(object())
    
    Traceback (most recent call last):
      File "", line 1, in 
        object().__eq__(object())
    AttributeError: 'object' object has no attribute '__eq__'
    

    * or rather, as roippi's answer points out, hardly ever, assuming sensible __eq__ implementations elsewhere.

提交回复
热议问题