We often take for granted the fact that you can use operators like +, -, == on python builtin data types. However, in reality this functionality has actually been coded into the classes by python. This means that we can code this functionality into our own classes by creating some special methods.
Take for an example the following class and objects:
If we would like to compare two points for equality we would have to do something like this:
This is far from elegant and is extremely inefficient. To solve this problem we can overload the default python method __eq__.
classPoint():def__init__(self,x=0,y=0):self.x=xself.y=yself.coords=(self.x,self.y)defmove(self,x,y):self.x+=xself.y+=ydef__eq__(self,other):returnself.x==other.xandself.y==other.yp1=Point(3,4)p2=Point(3,2)p3=Point(1,3)p4=Point(0,1)# Now we can compare points using ==isSame=p1==p2print(isSame)# Prints False
There are tons of other python default methods that we can overload. Some of the most used are featured below.
Now you may notice that when we try to print one of our point objects we get some cryptic text that looks like this
This is because we have not defined how our point should be represented as a string. To do this we must overload the __str__ method.
classPoint():def__init__(self,x=0,y=0):self.x=xself.y=yself.coords=(self.x,self.y)defmove(self,x,y):self.x+=xself.y+=ydef__str__(self):return"Point("+str(self.x)+','+str(self.y)+")"p1=Point(3,4)print(p1)# This prints Point(3, 4)
We can also overload the methods below to implement the comparison operators.
classPoint():def__init__(self,x=0,y=0):self.x=xself.y=yself.coords=(self.x,self.y)defmove(self,x,y):self.x+=xself.y+=ydeflength(self):importmathreturnmath.sqrt(self.x**2+self.y**2)def__gt__(self,other):# greater thanreturnself.length()>other.length()def__ge__(self,other):# greater than or equal toreturnself.length()>=other.length()def__lt__(self,other):# less thanreturnself.length()<other.length()def__le__(self,other):# less than or equal toreturnself.length()<=other.length()# We are going to compare points based on their lengthsp1=Point(3,4)p2=Point(3,2)p3=Point(1,3)p4=Point(0,1)isLess=p1<=p2# This is Falseprint(isLess)
To see a list of all over-loadable methods please click here.