Just to fill a gap, remember that Python allows for operator overloading. That is, you can override functions like __add__
, __cmp__
etc. to provide support for such operators. For example:
In [1]:
class Student(object):
def __init__(self, name, rollno, score):
self.name = name
self.rollno = rollno
self.score = score
def __repr__(self):
return "%s (%s)" % (self.name, self.rollno)
def __lt__(self, other):
return self.score < other.score
s1 = Student('Adam', 'A1', 30)
s2 = Student('Bob', 'A2', 40)
s3 = Student('Carol', 'A3', 50)
print("Checking if %s has outscored %s..." % (s2, s1))
print(s1 < s2)
print("Checking if %s has outscored %s..." % (s2, s3))
print(s2 > s3)
print(sorted([s1, s3, s2]))
In the above, two special operators are being overridden.
One is the "less than" operator __lt__
, that checks the score of students and allows for ordering based on that. This means that functions like sorted
can be called without a special key! Note that you also get the __gt__
for free. What happens when two students have equal scores is left as an exercise.
The other operator is __repr__
. That is called when a string operator is required. It is much better to override this, since that way, you can see a neat description of your object, rather than <__main__.Student instance at 0x7fdcdb58fc68>