
Ranking the Guild
sorted(), max() and < all use __lt__ ("less than"). There are
six comparison dunders (__lt__, __le__, __gt__, __ge__,
__eq__, __ne__), but writing all of them is tedious.
functools.total_ordering is a class decorator that fills in the rest
once you define __eq__ and one ordering method:
from functools import total_ordering
@total_ordering
class Coin:
def __init__(self, value):
self.value = value
def __eq__(self, other):
if not isinstance(other, Coin):
return NotImplemented
return self.value == other.value
def __lt__(self, other):
if not isinstance(other, Coin):
return NotImplemented
return self.value < other.value
Coin(5) >= Coin(2) # True -- written for you
Pip tip: Defining
__eq__sets__hash__toNone, so the objects can't go in sets or be dict keys unless you also define__hash__(e.g.return hash(self.value)).
Assignment
Fill the ___ blanks so Rank objects compare by their position in
RANKS (an apprentice is lower than a keeper, and so on), and all six
comparisons work.
Fill the ___ blanks so Rank objects compare by their position in
RANKS (an apprentice is lower than a keeper, and so on), and all six
comparisons work.
Press Run to try your code, then Check to test it.