Created
April 3, 2018 23:06
-
-
Save jfly/98a6140a3f15a724dab6f9c9f1a03416 to your computer and use it in GitHub Desktop.
Playing around with python's rich comparison operators
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from __future__ import print_function | |
import functools | |
@functools.total_ordering | |
class Comparable(): | |
def __init__(self, value): | |
self._value = value | |
def __lt__(self, o): | |
return self._value < o._value | |
def __eq__(self, o): | |
return self._value == o._value | |
#<<< def __cmp__(self, o): | |
#<<< return self._value - o._value | |
def __repr__(self): | |
return "{}".format(self._value) | |
one = Comparable(1) | |
two = Comparable(2) | |
other_one = Comparable(1) | |
def every_operator(val1, val2): | |
print("{} == {}: {}".format(val1, val2, val1 == val2)) | |
print("{} < {}: {}".format(val1, val2, val1 < val2)) | |
print("{} <= {}: {}".format(val1, val2, val1 <= val2)) | |
print("{} > {}: {}".format(val1, val2, val1 > val2)) | |
print("{} >= {}: {}".format(val1, val2, val1 >= val2)) | |
every_operator(one, one) | |
print() | |
every_operator(one, two) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I was toying around with this after reading http://portingguide.readthedocs.io/en/latest/comparisons.html.