Why does Python have an __ne__ operator method instead of just __eq__?

后端 未结 3 801
南方客
南方客 2020-12-05 09:51

The answer here gives a handwaving reference to cases where you\'d want __ne__ to return something other than just the logical inverse of __eq__, b

相关标签:
3条回答
  • 2020-12-05 10:06

    Some libraries do fancy things and don't return a bool from these operations. For example, with numpy:

    >>> import numpy as np
    >>> np.array([1,2,5,4,3,4,5,4,4])==4
    array([False, False, False,  True, False,  True, False,  True,  True], dtype=bool)
    >>> np.array([1,2,5,4,3,4,5,4,4])!=4
    array([ True,  True,  True, False,  True, False,  True, False, False], dtype=bool)
    

    When you compare an array to a single value or another array you get back an array of bools of the results of comparing the corresponding elements. You couldn't do this if x!=y was simply equivalent to not (x==y).

    0 讨论(0)
  • 2020-12-05 10:13

    SQLAlchemy is a great example. For the uninitiated, SQLAlchemy is a ORM and uses Python expression to generate SQL statements. In a expression such as

    meta.Session.query(model.Theme).filter(model.Theme.id == model.Vote.post_id)
    

    the model.Theme.id == model.VoteWarn.post_id does not return a boolean, but a object that eventually produces a SQL query like WHERE theme.id = vote.post_id. The inverse would produce something like WHERE theme.id <> vote.post_id so both methods need to be defined.

    0 讨论(0)
  • 2020-12-05 10:15

    More generally, in many valued logic systems, equals and not equals are not necessarily exact inverses of each other.

    The obvious example is SQL where True == True, False == False and Null != Null. Although I don't know if there are any specific Python examples I can imagine it being implemented in places.

    0 讨论(0)
提交回复
热议问题