Skip to content

Instantly share code, notes, and snippets.

@white-gecko
Created October 31, 2019 12:25
Show Gist options
  • Save white-gecko/b0b21461fd6d9a29a39ea7bdfa32453f to your computer and use it in GitHub Desktop.
Save white-gecko/b0b21461fd6d9a29a39ea7bdfa32453f to your computer and use it in GitHub Desktop.
Play around with a hashable and comparable object in python
#!/usr/bin/env python3
class mE():
def __init__(self, value):
self.v = value
# we need __hash__ and __eq__ for the set
def __hash__(self):
# the maximum length of hash is restricted by the platform:
# https://docs.python.org/3/reference/datamodel.html#object.__hash__
# if the string exceeds this length we need to do:
# return hash(ord(self.v.lower()))
return ord(self.v.lower())
def __eq__(self, other):
return hash(self) == hash(other)
# we need __lt__ and __le__ for the object to be comparable
def __lt__(self, other):
return hash(self) < hash(other)
def __le__(self, other):
return hash(self) <= hash(other)
# if __lt__ and __le__ are implemented __gt__ and __ge__ are optional
# def __gt__(self, other):
# return hash(self) > hash(other)
#
# def __ge__(self, other):
# return hash(self) >= hash(other)
# we need __str__ when str() or print() is called
def __str__(self):
return self.v
# we need __repr__() when the set is printed that contains instances
def __repr__(self):
return "mE(v: '{}')".format(self.v)
a = set([mE('A'), mE('a'), mE('b'), mE('c'), mE('D'), mE('d')])
b = set([mE('A'), mE('B')])
print(mE('A') != mE('a'))
print(mE('A') != mE('B'))
print(mE('A') < mE('B'))
print(mE('A') > mE('B'))
print(mE('A') <= mE('B'))
print(mE('A') >= mE('B'))
print(mE('A'))
print(mE('a'))
print(sorted(a))
print(sorted(a-b))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment