8.2. Operator Comparison

  • > (Greater than)

  • < (Less than)

  • == (Equal to)

  • != (Not equal to)

  • >= (Greater than or equal to)

  • <= (Less than or equal to)

8.2.1. SetUp

>>> from dataclasses import dataclass

8.2.2. Example

  • obj == other -> obj.__eq__(other)

  • obj != other -> obj.__ne__(other)

  • obj < other -> obj.__lt__(other)

  • obj <= other -> obj.__le__(other)

  • obj > other -> obj.__gt__(other)

  • obj >= other -> obj.__ge__(other)

>>> @dataclass
... class Vector:
...     x: int
...     y: int
...
...     def __eq__(self, other): ...  # ==
...     def __ne__(self, other): ...  # !=
...     def __lt__(self, other): ...  # <
...     def __le__(self, other): ...  # <=
...     def __gt__(self, other): ...  # >
...     def __ge__(self, other): ...  # >=

8.2.3. Use Case 0x01

>>> import numpy as np
>>>
>>> a = np.array([[1, 2, 3],
...               [4, 5, 6],
...               [7, 8, 9]])

Equal:

>>> a == 5
array([[False, False, False],
       [False,  True, False],
       [False, False, False]])
>>>
>>> a.__eq__(5)
array([[False, False, False],
       [False,  True, False],
       [False, False, False]])

Not Equal:

>>> a != 5
array([[ True,  True,  True],
       [ True, False,  True],
       [ True,  True,  True]])
>>>
>>> a.__ne__(5)
array([[ True,  True,  True],
       [ True, False,  True],
       [ True,  True,  True]])

Less Than:

>>> a < 5
array([[ True,  True,  True],
       [ True, False, False],
       [False, False, False]])
>>>
>>> a.__lt__(5)
array([[ True,  True,  True],
       [ True, False, False],
       [False, False, False]])