Defining Comparisons





Comparable objects recognize the comparison operators ==, !=, <, >, =<, and >=.  Strings are comparable. The str class includes the methods __eq__ and __lt__. Using these two methods, Python automatically generates the code for the appropriate comparisons when it encounters any of the other comparison operators that are used with strings.


A list of strings can be sorted using the sort() method, but a list of Student objects cannot.  However, the programmer can include the __eq__ and __lt__ methods in the Student class to solve this problem.  Each method uses the studentsŐ names as the comparable attributes.


Note that the concepts of less than and greater than are more restrictive than equality.  That is, the types of objects being compared are now assumed to be the same, so any errors will be raised at run time.




class Student:


    NUM_GRADES = 5


    def __init__(self, name): = name

        self.grades = []

        for i in range(Student.NUM_GRADES):



    def __eq__(self, other):

        if self is other:

            return True

        elif type(self) != type(other):

            return False


            return ==


    def __lt__(self, other):

        return <




s1 = Student('Mary')

s2 = Student('Bill')

print(s1 < s2)            # displays False

print(s1 > s2)            # displays True



A class of comparable objects implements the Comparable interface.  For example, the String class implements Comparable.  This interface specifies a single compareTo method, as follows:


public interface Comparable<E>{


    public int compareTo(E element);



This interface is generic; the element type E is filled in by the implementing class (usually, the name of that class itself).  The method compares the relevant attributes of the receiver object and the parameter object.  compareTo returns 0 if the two objects are equal (using the equals method), an integer less than 0 if the receiver is less than the parameter, and an integer greater than 0 otherwise.  The following example uses the studentsŐ names as the comparable attributes:




public class Student implements Comparable<Student>{


    private String name;


    public Student(String name){ = name;



    public int compareTo(Student other){

























Student s1 = new Student("Mary");

Student s2 = new Student("Bill");

System.out.println(s1.comapreTo(s2) < 0);   // displays false

System.out.println(s1.compareTo(s2) > 0);   // displays true