Making your Class Comparable

Let us suppose that we want to know if one die is “equal to” another die. What does that mean? Does it mean that the same number is up on the face of the die? What if one die is a 10 sided die and the other only six? Could those two dice ever be equal?

With Python we get to decide what it means for two dice to be equal to each other. We express what that means in code by writing the __eq__ method for our MSDie class. Not only does this allow us to define the rules but it also allows us to use the standard operators in our code, for example we could write die1 == die2 to check if they are equal. Further, we can write several different methods for all manner of comparisons that we may want to make including:

Let us look at an implementation of the __eq__ method.

Notice that the __eq__ method has two formal parameters, self as usual and other other represents the die to which we want to compare. You can think of it as though we are testing self == other.

Lets try these operations in action in the next activecode. Before you run them answer the questions following the example.

You might think it would be tedius to write all of the comparison functions but in fact it appears that just three are required. __eq__, __lt__, and __le__. What happens if you do not write __le__?

What happens if you only write the functions __eq__, __gt__, __ge__?

So what is python doing? It is providing default implementations of some of the comparison operators in the parent class! It does this by writing them by calling the “dunder methods” directly and using logic.

Can you write versions of __ne__, __gt__, __ge__ in terms of __eq__, __lt__, __le__?

You have attempted of activities on this page