CP164 Final: Class Methods
Class Methods
Sorting Lists of Objects
Having defined a Student class we could add Student objects to Python lists and tuples.
(Doing so is left as an exercise to you.) A common list method is sort - arranging the
contents of a list in order. However, Python has to know how to compare two objects.
Without comparisons defined, we get errors as in this code:
students = []
# fill students with Student objects
# attempt to sort the lis
students.sort()
Traceback (most recent call last):
students.sort()
TypeError: unorderable types: Student() < Student()
Python sees the Student objects as unorderable because it has no way of comparing these
objects. With the boolean methods correctly defined, however, Python can easily
sort Student objects.We must define the methods.
The __eq__ Method
It is often necessary to be able to compare two objects for equality. Defining
a __eq__ method for a class allows you to compare any two objects of the same class with
the standard == operator, as in this example:
def __eq__(self, other):
"""
-------------------------------------------------------
Compares against another student for equality.
Use: student == other
-------------------------------------------------------
Parameters:
other - other student to compare to (Student)
Returns:
result - True if student IDs match, False otherwise (boolean)
-------------------------------------------------------
"""
result = self.student_id == other.student_id
return result
This is a very simple object comparison, comparing only the student IDs of the two objects.
Thus two student objects, student1 and student2, can be compared in an if statement with:
if student1 == student2:
Document Summary
Having defined a student class we could add student objects to python lists and tuples. (doing so is left as an exercise to you. ) A common list method is sort - arranging the contents of a list in order. However, python has to know how to compare two objects. Without comparisons defined, we get errors as in this code: students = [] Python sees the student objects as unorderable because it has no way of comparing these objects. With the boolean methods correctly defined, however, python can easily sort student objects. we must define the methods. It is often necessary to be able to compare two objects for equality. Defining a __eq__ method for a class allows you to compare any two objects of the same class with the standard == operator, as in this example: def __eq__(self, other): Parameters: other - other student to compare to (student)