This Python __lt__ lesson is for a beginner. Read the short notes, run each example, then change one name or number and run it again.
__lt__ defines the < comparison. sorted uses it when you do not pass a key.
Return True or False. Do not return the difference of the numbers.
Example 1: Start here
The smaller score sorts first, so the first item is 70.
class Score: # a template for objects
def __init__(self, value): # runs when you create the object
self.value = value # store this on the object
def __lt__(self, other): # define the function; it runs when you call it
return self.value < other.value # send this value back to the caller
print(sorted([Score(90), Score(70)])[0].value) # a new list, sorted
Example 2: Sort objects
__lt__ is the less-than test sort uses.
class Score: # a template for objects
def __init__(self, value): # runs when you create the object
self.value = value # store this on the object
def __lt__(self, other): # define the function; it runs when you call it
return self.value < other.value # send this value back to the caller
def __repr__(self): # define the function; it runs when you call it
return str(self.value) # send this value back to the caller
scores = [Score(82), Score(60), Score(91)] # a list; the values stay in this order
scores.sort() # sort this list in place
print(scores)
Example 3: A direct comparison
The < operator calls __lt__.
class Score: # a template for objects
def __init__(self, value): # runs when you create the object
self.value = value # store this on the object
def __lt__(self, other): # define the function; it runs when you call it
return self.value < other.value # send this value back to the caller
print(Score(60) < Score(82)) # a comparison is True or False
Example 4: Compare one field
Only the score decides the order. The name is ignored.
class Student: # a template for objects
def __init__(self, name, score): # runs when you create the object
self.name = name # store this on the object
self.score = score # store this on the object
def __lt__(self, other): # define the function; it runs when you call it
return self.score < other.score # send this value back to the caller
print(Student("Arun", 74) < Student("Meera", 82)) # a comparison is True or False
