The Functools Module
This class extends the tuple class; it has no additional slots, thereby making it
immutable. We've overridden the new() method so that we can seed initial
values of a rank and a suit. We've provided a repr() method to print a string
representation of a Card. We've provided two properties to extract a rank and a suit
using attribute names.
The rest of the class definition shows how we can define just two comparisons:
def eq(self, other):
if isinstance(other,Card):
return self.rank == other.rank
elif isinstance(other,Number):
return self.rank == other
def lt(self, other):
if isinstance(other,Card):
return self.rank < other.rank
elif isinstance(other,Number):
return self.rank < other
We've defined the eq() and lt() functions. The @total_ordering
decorator handles the construction of all other comparisons. In both cases, we've
allowed comparisons between cards and also between a card and a number.
First, we get proper comparison of only the ranks as follows:
c2s= Card(2, '\u2660')
c2h= Card(2, '\u2665')
c2h == c2s
True
c2h == 2
True
We can use this class for a number of simulations with simplified syntax to
compare ranks of cards. Further, we also have a rich set of comparison operators
as follows:
c2s= Card(2, '\u2660')
c3h= Card(3, '\u2665')
c4c= Card(4, '\u2663')
c2s <= c3h < c4c
True
c3h >= c3h