osdir.com


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Why does __ne__ exist?


When you create a Python class, you can create dunder methods to
define how your objects respond to the standard operators. With
comparison operators, Python will happily switch the operands around
to find a method to call:

>>> class Spam():
...     def __lt__(self, other):
...         print("%s is less than %s" % (self, other))
...         return True
...
>>> Spam() < 2
<__main__.Spam object at 0x7fb7557b1fd0> is less than 2
True
>>> 3 > Spam()
<__main__.Spam object at 0x7fb7557b1fd0> is less than 3
True
>>> 4 > Spam() < 5
<__main__.Spam object at 0x7fb7557b1fd0> is less than 4
<__main__.Spam object at 0x7fb7557b1fd0> is less than 5
True

But Python will not automatically assume the converse:

>>> Spam() >= 6
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: '>=' not supported between instances of 'Spam' and 'int'
>>> Spam() > 7
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: '>' not supported between instances of 'Spam' and 'int'

This is good. This is correct. For inequalities, you can't assume that
>= is the exact opposite of < (for example, sets don't behave like
numbers, so "x <= y" is very different from )