Python's preferred comparison operators

前端 未结 4 1241
青春惊慌失措
青春惊慌失措 2020-12-15 05:12

Is it preferred to do:

if x is y:
    return True

or

if x == y
    return True

Same thing for \"is not\"<

4条回答
  •  一生所求
    2020-12-15 05:21

    x is y compares the identities of the two objects, and is asking 'are x and y different names for the same object?' It is equivalent to id(x) == id(y).

    x == y uses the equality operator and asks the looser question 'are x and y equal?' For user defined types it is equivalent to x.__eq__(y).

    The __eq__ special method should represent 'equalness' for the objects, for example a class representing fractions would want 1/2 to equal 2/4, even though the 'one half' object couldn't have the same identity as the 'two quarters' object.

    Note that it is not only the case that a == b does not imply a is b, but also the reverse is true. One is not in general a more stringent requirement than the other. Yes, this means that you can have a == a return False if you really want to, for example:

    >>> a = float('nan')
    >>> a is a
    True
    >>> a == a
    False
    

    In practice though is is almost always a more specific comparison than ==.

提交回复
热议问题