Learning Python: Programming and Data Structures- Tutorial 9- Operator Overloading

Operator Overloading mean, that we re-define certain common operators and methods, to work in a customized manner.

Say, we have a class which holds academic records for Students. And, when we say that student1 < student2;  we mean to say that the aggregate scores of Student2 are higher than the same for Student1.
For this, we will override the __lt__ (less than) function, in class Student to behave in this customized manner.Similarly, we can redefine the addition operator (+), multiplication, subtraction, power operators by redefining the __add__, __mult__, __sub__, __pow__ functions.
Take a look at the special method names over here:  Special method namesThis will give you an idea of method names which can be overridden.
Let us take a quick look at this simple example for students, described above. We are going to overload the > operator (greater than) in this example.

# Let's define a class student, with the name of the student, and the student's score in Math and English

class student: def __init__(self,name,percentageScoreInMathematics,percentageScoreInEnglish): self.name = name self.percentageScoreInMathematics = percentageScoreInMathematics self.percentageScoreInEnglish = percentageScoreInEnglish

# This is where we will try out overloading

# We will overload the > symbol. # So, we include this __gt__ function (lt stands for less than) # Student1 is supposed to be 'greater than' student 2 if his aggregate score in Math and English is greater than that of Student2 def __gt__(self,secondStudent): return (self.percentageScoreInMathematics + self.percentageScoreInEnglish) > (secondStudent.percentageScoreInMathematics + secondStudent.percentageScoreInEnglish) # A function to display the name and scores(in Math and English) of the student def displayDetails(self): print self.name + " Mathematics Score =" + `self.percentageScoreInMathematics` + " English Score =" + `self.percentageScoreInEnglish` + '\n'

# Let us create 2 objects corresponding to two students

firstStudent = student('Ankit',98,99) secondStudent = student('Jack',90,95)

# Let us display the details of these two students

firstStudent.displayDetails() secondStudent.displayDetails()

# Now let us use the overloaded > operator to compare the two students and find out who is the better one in terms of aggregate scores

print "Records of the better student:" print "We will use the overridden > operator to do this" # Now we will compare the two students with the overloaded 'greater than' > sign if firstStudent > secondStudent: firstStudent.displayDetails() else: secondStudent.displayDetails()

Output from the above program:

~/work/pythontutorials$ python operatorOverloading.py 
Ankit Mathematics Score =98 English Score =99

Jack Mathematics Score =90 English Score =95

Records of the better student:
We will use the overridden > operator to do this
Ankit Mathematics Score =98 English Score =99