Skip to content

Instantly share code, notes, and snippets.

@IndhumathyChelliah
Created Jul 2, 2020
Embed
What would you like to do?
class Student:
def __init__(self,name,rollno,age):
self.name=name
self.rollno=rollno
self.age=age
def __str__(self):
return "{}-{}-{}".format(self.name,self.rollno,self.age)
def __lt__(self,other):
return (self.age<other.age)
def __le__(self,other):
return (self.age<=other.age)
def __gt__(self,other):
return (self.age>other.age)
def __ge__(self,other):
return (self.age>=other.age)
def __eq__(self,other):
return (self.age==other.age)
def __ne__(self,other):
return (self.age!=other.age)
s1=Student("karthi",12,7)
s2=Student("Sarvesh",15,3)
#when trying to do comparison operator "<" two class objects,magic method __lt__() is invoked.
#It will compare age attribute of two Student objects according to the behavior mentioned in the method __lt__()
print (s1<s2)#Output:False
#when trying to compare "<=" two class objects,magic method __le__() is invoked
print (s1<=s2)#Output:False
#when trying to compare ">" two class objects,magic method __gt__() is invoked
print (s1>s2)#Output:True
#when trying to comapre ">=" two class objects,magic method __ge__() is invoked
print (s1>=s2)#Ouput:True
#when trying to do equality operation on two class objects,magic method __eq__() is invoked
print (s1==s2)#Output:False
#when trying to perform (not equal) operation on two class objects,magic method __ne__() is invoked
print (s1!=s2)#Output:True
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment