CP164 Final: class - method
![](https://new-preview-html.oneclass.com/R6r8MpaPXwB5NbLV3OoDmlg2z1GYy93Z/bg1.png)
The __lt__ Method
Defining a __lt__ method for a class allows you to use the < operator to compare two
objects, as well as its negation, the >= operator. For the Student class:
def __lt__(self, other):
"""
-------------------------------------------------------
Determines if this student precedes another.
If student IDs don't match (using already defined == operator),
compares students by name then by ID.
Use: student < other
-------------------------------------------------------
Parameters:
other - other student to compare to (Student)
Returns:
result - True if student less than other, False otherwise
(boolean)
-------------------------------------------------------
"""
if self == other:
result = False
else:
# Compare the data values by putting them into tuples.
result = \
(self.surname.lower(), self.forename.lower(),
self.birth_date) < \
(other.surname.lower(), other.forename.lower(),
other.birth_date)
return result
Now we can compare two Student objects as in these examples:
if student1 < student2:
...
if student1 >= student2:
...
Note that the __lt__ code uses a Python shortcut to compare the names and IDs of
two Student objects. By putting the string values into tuples, the function then compares
the two tuples to determine its result. This is the equivalent of the following code:
if self.surname.lower() < other.surname.lower():
result = True
elif self.surname.lower() == other.surname.lower():
if self.forename.lower() < other.forename.lower():
result = True
elif self.forename.lower() == other.forename.lower():
if self.birth_date < other.birth_date:
result = True
else:
Document Summary
Defining a __lt__ method for a class allows you to use the < operator to compare two objects, as well as its negation, the >= operator. If student ids don"t match (using already defined == operator), compares students by name then by id. Parameters: other - other student to compare to (student) Returns: result - true if student less than other, false otherwise (boolean) if self == other: result = false else: # compare the data values by putting them into tuples. result = \ (self. surname. lower(), self. forename. lower(), self. birth_date) < \ (other. surname. lower(), other. forename. lower(), other. birth_date) return result. Now we can compare two student objects as in these examples: if student1 < student2: if student1 >= student2: Note that the __lt__ code uses a python shortcut to compare the names and ids of two student objects. By putting the string values into tuples, the function then compares the two tuples to determine its result.