CP164 Final: class - method

29 views2 pages
13 Jun 2018
School
Course
Professor
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:
Unlock document

This preview shows half of the first page of the document.
Unlock all 2 pages and 3 million more documents.

Already have an account? Log in

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.

Get access

Grade+
$40 USD/m
Billed monthly
Grade+
Homework Help
Study Guides
Textbook Solutions
Class Notes
Textbook Notes
Booster Class
10 Verified Answers

Related Documents