In real-world applications, you may need to compare two custom objects that you have defined.
Maybe you need to compare them based on certain criteria, or their certain attributes.
Let’s say you have a class called Game and you want to be able to compare games based on their scores.
If you try to do compare them right away, you are going to get an error, since you haven’t defined a method that Python uses underneath the table to do the actual comparison.
We are going to implement that so that we don’t get this exception.
This method is __lt__():
Now, if we try to compare, let’s say, two objects of the Game class, we are going to compare them based on their scores:
That’s pretty much how you implement it.
You can analogously implement:
- __sub__() for –
- __add__() for +
- __eq__() for =
- __mul__() for *
- __truediv__() for /
- __ne__() forĀ !=
- __ge__() for >=
- __gt__() for >
I hope you find this useful.